<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;
use PHPExcel;
use PHPExcel_Writer_Excel5;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Fill;
use PHPExcel_Style_Border;
use PHPExcel_Cell_DataType;

class Apapply extends Commonwork
{
    //ap预算匹配
    public function apdys($did){
        $applyde=Db::table("ap_apply_detail")->where(["id"=>$did])->select();
        $apply=Db::table("ap_apply")->where(["id"=>$applyde[0]["apply_id"]])->find();
        $aptar=Db::table("target_format")->where(["type_id"=>3])->find();
        $aid=$apply["id"];
        if($aptar){
            $yusuan=[];

            for($i=0;$i<count($applyde);$i++){
                $where="type=2 ";
                $sanjifeiyong=$applyde[$i]["feiyong_id"];
                $erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
                $yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
                $start=strtotime($applyde[$i]["start_time"]);
                $end=strtotime($applyde[$i]["end_time"]);
                $tianshu=($end-$start)/24/3600+1;
                //echo $tianshu;
                if($aptar["channel_id"]){
                    $where.="and channel1={$apply["channel_id"]} ";
                }
                if($aptar["product_id"]){
                    if($aptar["product_id"]==11){
                        $where.="and pinpai={$applyde[$i]["brand"]} and pinlei is null and xilie is null ";
                    }else if($aptar["product_id"]==12){
                        if($applyde[$i]["category"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie is null ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }else if($aptar["product_id"]==13){
                        if($applyde[$i]["series"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie={$applyde[$i]["series"]} ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }
                }else{
                    $where.="and pinpai is null and pinlei is null and xilie is null ";
                }
                if($aptar["area_id"]||$aptar["client_id"]){
                    if($aptar["area_id"]==20){
                        $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng is null and shi is null and jingxiao is null ";
                    }else if($aptar["area_id"]==21){
                        if($applyde[$i]["sheng"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi is null and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["area_id"]==22){
                        if($applyde[$i]["shi"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["client_id"]==8){
                        if($applyde[$i]["jxs"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao={$applyde[$i]["jxs"]} ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }
                }else{
                    $where.="and fenqu is null and sheng is null and shi is null and jingxiao is null ";
                }
                if($aptar["feiyong_id"]){
                    if($aptar["feiyong_id"]==16){
                        $where.="and sanjifeiyong=$sanjifeiyong ";
                    }else if($aptar["feiyong_id"]==15){
                        $where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
                    }else{
                        $where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
                    }
                }else{
                    $where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
                }
               // echo $where;
                if($aptar["kaoheqi"]==18){
                    //echo 1;
                    //二级考核期
                    $kaohes=Db::table("cg_kaoheqi2")->alias("k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->where("k2.endtime>=$start and k2.starttime<=$end")->field("k2.id,k2.title,k2.pid,k1.cid,k2.starttime,k2.endtime")->select();
                    for($j=0;$j<count($kaohes);$j++){
                        $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                        $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                        $ts=($jisuanend-$jisuanstart)/24/3600+1;
                        //echo "-".$ts;
                        $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and yijikaoheqi={$kaohes[$j]["pid"]} and erjikaoheqi={$kaohes[$j]["id"]}";
                        //echo $fullwhere;exit;
                        $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                        if($yusuanpipei){
                            $yusuanpipei["yid"]=$yusuanpipei["id"];$yusuan[]=$yusuanpipei;
                        }
                        //print_r($yusuanpipei);
                        
                    }
                }else{
                    //一级考核期
                    $kaohes=Db::table("cg_kaoheqi1")->where("endtime>=$start and starttime<=$end")->field("id,title,cid,starttime,endtime")->select();
                    for($j=0;$j<count($kaohes);$j++){
                        $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                        $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                        $ts=($jisuanend-$jisuanstart)/24/3600+1;
                        $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and yijikaoheqi={$kaohes[$j]["id"]} and erjikaoheqi is null";
                        //echo $fullwhere;exit;
                        $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                        if($yusuanpipei){
                            $yusuanpipei["yid"]=$yusuanpipei["id"];$yusuan[]=$yusuanpipei;
                        }
                    }
                }
            }
            //print_r($yusuan);exit;
            return $yusuan;
        }else{
            return [];//未设定格式
        }
       
    }
    public function mingxijuece($did){
        $de=Db::Table("ap_apply_detail")->where(["id"=>$did])->find();
        $de["channel1"]=Db::table("ap_apply")->where(["id"=>$de["apply_id"]])->value("channel_id");
        $de["sanjifeiyong"]=$de["feiyong_id"];
        $de["erjifeiyong"]=Db::table("cg_feiyongkemu3")->where(["id"=>$de["feiyong_id"]])->value("pid");
        $de["yijifeiyong"]=Db::table("cg_feiyongkemu2")->where(["id"=>$de["erjifeiyong"]])->value("pid");
        $de["starttime"]=strtotime($de["start_time"]);$de["endtime"]=strtotime($de["end_time"]);
        $zongtianshu=($de["endtime"]-$de["starttime"])/24/3600+1;
        //print_r($de);
        $state=Db::table("ap_apply")->where(["id"=>$de["apply_id"]])->value("state");
        if($state==1){
            //草稿无预算
            $ys=$this->apdys($did);
        }else{
            //申请有预算
            $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where(["y.type"=>2,"yd.did"=>$did])->select();
        }
        //print_r($de);
        $juece="";
        //print_r($ys);exit;
        if($ys){
            //有预算
            if($ys[0]["jingxiao"]){
                $jxs=Db::table("cg_jxs")->where(["id"=>$ys[0]["jingxiao"]])->value("title");
                $juece.="经销商:{$jxs}&nbsp;&nbsp;";
            }else if($ys[0]["shi"]){
                $shi=Db::table("cg_market_city")->where(["id"=>$ys[0]["shi"]])->value("title");
                $juece.="城市:{$shi}&nbsp;&nbsp;";
            }else if($ys[0]["sheng"]){
                $sheng=Db::table("cg_market_provice")->where(["id"=>$ys[0]["sheng"]])->value("title");
                $juece.="省份:{$sheng}&nbsp;&nbsp;";
            }else{
                $fenqu=Db::table("cg_market_zoning")->where(["id"=>$de["fenqu"]])->value("title");
                $juece.="分区:{$fenqu}&nbsp;&nbsp;";
            }
            if($ys[0]["sanjifeiyong"]){
                $sanji=Db::table("cg_feiyongkemu3")->where(["id"=>$ys[0]["sanjifeiyong"]])->value("title");
                $juece.="三级费用科目:{$sanji}&nbsp;&nbsp;";
            }else if($ys[0]["erjifeiyong"]){
                $erji=Db::table("cg_feiyongkemu2")->where(["id"=>$ys[0]["erjifeiyong"]])->value("title");
                $juece.="二级费用科目:{$erji}&nbsp;&nbsp;";
            }else{
                $yiji=Db::table("cg_feiyongkemu1")->where(["id"=>$de["yijifeiyong"]])->value("title");
                $juece.="一级费用科目:{$yiji}&nbsp;&nbsp;";
            }
            $channel1=Db::table("cg_channel_types1")->where(["id"=>$de["channel1"]])->value("title");
            $juece.="一级渠道:{$channel1}&nbsp;&nbsp;";
            if($ys[0]["erjikaoheqi"]){
                
                $juece.="考核期:二级考核期";
                $kaohe=2;
            }else{
                $juece.="考核期:一级考核期";
                $kaohe=1;
            }
        }else{
            //无预算
            $tar=Db::table("target_format")->where(["type_id"=>3])->find();
            if($tar["area_id"]){
                if($tar["area_id"]==8){
                    $jxs=Db::table("cg_jxs")->where(["id"=>$de["jingxiao"]])->value("title");
                    $juece.="经销商:{$jxs}&nbsp;&nbsp;";
                }else if($tar["area_id"]==22){
                    $shi=Db::table("cg_market_city")->where(["id"=>$de["shi"]])->value("title");
                    $juece.="城市:{$shi}&nbsp;&nbsp;";
                }else if($tar["area_id"]==21){
                    $sheng=Db::table("cg_market_provice")->where(["id"=>$de["sheng"]])->value("title");
                    $juece.="省份:{$sheng}&nbsp;&nbsp;";
                }else{
                    $fenqu=Db::table("cg_market_zoning")->where(["id"=>$de["fenqu"]])->value("title");
                    $juece.="分区:{$fenqu}&nbsp;&nbsp;";
                }
            }else{
                $fenqu=Db::table("cg_market_zoning")->where(["id"=>$de["fenqu"]])->value("title");
                $juece.="分区:{$fenqu}&nbsp;&nbsp;";
            }
            if($tar["feiyong_id"]){
                if($tar["feiyong_id"]==16){
                    $sanji=Db::table("cg_feiyongkemu3")->where(["id"=>$de["sanjifeiyong"]])->value("title");
                    $juece.="三级费用科目:{$sanji}&nbsp;&nbsp;";
                }else if($tar["feiyong_id"]==15){
                    $erji=Db::table("cg_feiyongkemu2")->where(["id"=>$de["erjifeiyong"]])->value("title");
                    $juece.="二级费用科目:{$erji}&nbsp;&nbsp;";
                }else{
                    $yiji=Db::table("cg_feiyongkemu1")->where(["id"=>$de["yijifeiyong"]])->value("title");
                    $juece.="一级费用科目:{$yiji}&nbsp;&nbsp;";
                }
            }else{
                $yiji=Db::table("cg_feiyongkemu1")->where(["id"=>$de["yijifeiyong"]])->value("title");
                $juece.="一级费用科目:{$yiji}&nbsp;&nbsp;";
            }
            $channel1=Db::table("cg_channel_types1")->where(["id"=>$de["channel1"]])->value("title");
            $juece.="一级渠道:{$channel1}&nbsp;&nbsp;";
            if($tar["kaoheqi"]==17){
                $juece.="考核期:一级考核期";
                $kaohe=1;
            }else{
                $juece.="考核期:二级考核期";
                $kaohe=2;
            }
        }
        $this->assign("juece",$juece);
        if($kaohe==1){
            $kaoheqi=Db::table("cg_kaoheqi1")->alias("k1")
            ->join("cg_cainian c","k1.cid=c.id")
            ->where("k1.starttime<={$de["endtime"]} and k1.endtime>={$de["starttime"]}")->order("k1.starttime")
            ->field("k1.title as ktitle,k1.id as kid,c.id as cid,c.title as ctitle,k1.starttime,k1.endtime")->select();
        }else{
            $kaoheqi=Db::table("cg_kaoheqi2")->alias("k2")
            ->join("cg_kaoheqi1 k1","k2.pid=k1.id")
            ->join("cg_cainian c","k1.cid=c.id")
            ->where("k2.starttime<={$de["endtime"]} and k2.endtime>={$de["starttime"]}")->order("k2.starttime")
            ->field("k2.title as ktitle,k2.id as kid,c.id as cid,c.title as ctitle,k2.starttime,k2.endtime")->select();
        }
        $this->assign("kaoheqi",$kaoheqi);
        $ysshuju=[];//预算数据
        $sjshuju=[];//申请数据
        $heji=[];
        $yszong=0;
        $sjzong=0;
        $hezong=0;
        for($i=0;$i<count($kaoheqi);$i++){
            //填充预算数据
            if($ys){
                $flag=0;
                for($j=0;$j<count($ys);$j++){
                    if($kaohe==1){
                        if($ys[$j]["yijikaoheqi"]==$kaoheqi[$i]["kid"]){
                            $zys=Db::table("yusuan")->where(["id"=>$ys[$j]["yid"]])->value("jine");
                            $yyys=Db::table("yusuan_detail")->where(["yid"=>$ys[$j]["yid"],"type"=>2])->sum("jine");
                            if($yyys){
                                $ysshuju[]=$zys-$yyys;
                            }else{
                                $ysshuju[]=$zys;
                            }
                            //$ysshuju[]=Db::table("yusuan")->where(["id"=>$ys[$j]["yid"]])->value("jine");
                            $flag=1;break;
                        }
                    }else{
                        if($ys[$j]["erjikaoheqi"]==$kaoheqi[$i]["kid"]){
                            $zys=Db::table("yusuan")->where(["id"=>$ys[$j]["yid"]])->value("jine");
                            $yyys=Db::table("yusuan_detail")->where(["yid"=>$ys[$j]["yid"],"type"=>2])->sum("jine");
                            if($yyys){
                                $ysshuju[]=$zys-$yyys;
                            }else{
                                $ysshuju[]=$zys;
                            }
                            $flag=1;break;
                        }
                    }
                }
                if(!$flag){
                    $ysshuju[]=0;
                }
            }else{
                $ysshuju[]=0;
            }
            $yszong+=$ysshuju[$i];
            //填充申请数据
            $st=$de["starttime"]>=$kaoheqi[$i]["starttime"]?$de["starttime"]:$kaoheqi[$i]["starttime"];
            $ed=$de["endtime"]<=$kaoheqi[$i]["endtime"]?$de["endtime"]:$kaoheqi[$i]["endtime"];
            $ts=($ed-$st)/3600/24+1;
           // echo $ts."|"."$zongtianshu"."|";
            $sjshuju[]=($de["pifuzonge"]+($de["pifuzonge"]*$de["shuilv"]/100))/$zongtianshu*$ts;
            $sjzong+=$sjshuju[$i];
            $heji[]=$ysshuju[$i]-$sjshuju[$i];
            $hezong+=$heji[$i];
        }
        $this->assign("hezong",$hezong);
        $this->assign("sjzong",$sjzong);
        $this->assign("yszong",$yszong);
        $this->assign("heji",$heji);
        $this->assign("sjshuju",$sjshuju);
        $this->assign("ysshuju",$ysshuju);
        return $this->fetch();
    }
	public function shuju($aid){
		//exit;
			$applyde=Db::table("ap_apply")->alias("ap")
    		->join("ap_apply_detail apd","apd.apply_id=ap.id")
    		->join("ap_apply_detail yuanapd","apd.yuanmingxi=yuanapd.id","LEFT")
    		->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    		->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    		->join("cg_market_city c","apd.shi=c.id","LEFT")
    		->join("cg_jxs j","apd.jxs=j.id","LEFT")
    		->join("cg_system s","apd.system=s.id","LEFT")
    		->join("cg_net n","apd.net=n.id","LEFT")
    		->join("pro_brands pb","apd.brand=pb.id","LEFT")
    		->join("pro_category pc","apd.category=pc.id","LEFT")
    		->join("pro_series ps","apd.series=ps.id","LEFT")
    		->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    		->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    		->join("gys g","apd.gys=g.id")
    		->join("cg_paymethod cp","apd.zfid=cp.id")
    		->where(["ap.id"=>$aid,"apd.is_deleted"=>0])
    		->field("apd.id,apd.detail_no,apd.is_bu,g.no as gys_no,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.start_time,apd.end_time,k2.title as kemu2,apd.zonge,apd.pifuzonge,apd.shuilv,apd.dikou,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,cp.title as zffs,apd.zong_xiaoliang,apd.jizhun_xiaoliang,(apd.zong_xiaoliang-apd.jizhun_xiaoliang) as xinxiaoliang,apd.description,apd.remark,apd.tag,ap.no,yuanapd.start_time as yuanstart,yuanapd.end_time as yuanend,yuanapd.hexiao_time as yuanhexiao,apd.biandongyuanyin,apd.hexiao_time,apd.hexiao,apd.fankuixiaoliang,j.sn as jsn,s.sn as ssn,n.sn as nsn")
    		->select();
    			  Vendor("PHPExcel");
        
        
       Vendor("PHPExcel.Writer.Excel5");

       // Loader::import('PHPExcel.Classes.PHPExcel');
        //Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
       //  Vendor("Excel.PHPExcel.Writer.Excel2007");
        $objPHPExcel= new PHPExcel();
            
            
        $objProps=$objPHPExcel->getProperties();
            
        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");
            	
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("AP费用申请数据");

        #标题
        $objPHPExcel->getActiveSheet()->getStyle('1')->getAlignment()->setWrapText(true);
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(50);
         $objPHPExcel->getActiveSheet()->getStyle('2')->getAlignment()->setWrapText(true);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(50);
         //加粗
        $objPHPExcel->getActiveSheet()->getStyle('1')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('1')->getFont()->setSize(14);
                //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
                  //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
         $objPHPExcel->getActiveSheet()->getStyle('2')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A2:AA2')->getFill()->getStartColor()->setARGB('00FFFF00');
        $objPHPExcel->getActiveSheet()->setCellValue('A1',"项目描述");
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setARGB('00FF0000');
        $objPHPExcel->getActiveSheet()->setCellValue('B1',"供应商编号");
        $objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->getStartColor()->setARGB('00FF0000');
        $objPHPExcel->getActiveSheet()->setCellValue('C1',"供应商名称");
        $objPHPExcel->getActiveSheet()->getStyle('C1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('C1')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->setCellValue('D1',"分区");
        $objPHPExcel->getActiveSheet()->getStyle('D1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('D1')->getFill()->getStartColor()->setARGB('00FF0000');
        $objPHPExcel->getActiveSheet()->setCellValue('E1',"省份");
        $objPHPExcel->getActiveSheet()->getStyle('E1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('E1')->getFill()->getStartColor()->setARGB('0099CCFF');
        $objPHPExcel->getActiveSheet()->setCellValue('F1',"城市");
        $objPHPExcel->getActiveSheet()->getStyle('F1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('F1')->getFill()->getStartColor()->setARGB('0099CCFF');
        $objPHPExcel->getActiveSheet()->setCellValue('G1',"经销商编号");
        $objPHPExcel->getActiveSheet()->getStyle('G1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('G1')->getFill()->getStartColor()->setARGB('0099CCFF');
        $objPHPExcel->getActiveSheet()->setCellValue('H1',"经销商名称");
        $objPHPExcel->getActiveSheet()->getStyle('H1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('H1')->getFill()->getStartColor()->setARGB('0099CCFF');
          $objPHPExcel->getActiveSheet()->setCellValue('I1',"系统编号");
        $objPHPExcel->getActiveSheet()->getStyle('I1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('I1')->getFill()->getStartColor()->setARGB('0099CCFF');
        $objPHPExcel->getActiveSheet()->setCellValue('J1',"系统名称");
        $objPHPExcel->getActiveSheet()->getStyle('J1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('J1')->getFill()->getStartColor()->setARGB('0099CCFF');
          $objPHPExcel->getActiveSheet()->setCellValue('K1',"网点编号");
        $objPHPExcel->getActiveSheet()->getStyle('K1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('K1')->getFill()->getStartColor()->setARGB('0099CCFF');
        $objPHPExcel->getActiveSheet()->setCellValue('L1',"网点名称");
        $objPHPExcel->getActiveSheet()->getStyle('L1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('L1')->getFill()->getStartColor()->setARGB('0099CCFF');
          $objPHPExcel->getActiveSheet()->setCellValue('M1',"品牌");
        $objPHPExcel->getActiveSheet()->getStyle('M1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('M1')->getFill()->getStartColor()->setARGB('00FF0000');
          $objPHPExcel->getActiveSheet()->setCellValue('N1',"品类");
        $objPHPExcel->getActiveSheet()->getStyle('N1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('N1')->getFill()->getStartColor()->setARGB('0099CCFF');
          $objPHPExcel->getActiveSheet()->setCellValue('O1',"系列");
        $objPHPExcel->getActiveSheet()->getStyle('O1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('O1')->getFill()->getStartColor()->setARGB('0099CCFF');
        $objPHPExcel->getActiveSheet()->setCellValue('P1',"活动开始时间");
        $objPHPExcel->getActiveSheet()->getStyle('P1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('P1')->getFill()->getStartColor()->setARGB('00FF0000');
        $objPHPExcel->getActiveSheet()->setCellValue('Q1',"活动截至时间");
        $objPHPExcel->getActiveSheet()->getStyle('Q1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('Q1')->getFill()->getStartColor()->setARGB('00FF0000');

         $objPHPExcel->getActiveSheet()->setCellValue('R1',"三级费用科目");
        $objPHPExcel->getActiveSheet()->getStyle('R1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('R1')->getFill()->getStartColor()->setARGB('00FF0000');
         $objPHPExcel->getActiveSheet()->setCellValue('S1',"预计未税费用额");
        $objPHPExcel->getActiveSheet()->getStyle('S1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('S1')->getFill()->getStartColor()->setARGB('00FF0000');
          $objPHPExcel->getActiveSheet()->setCellValue('T1',"是否增值税(可抵扣)");
        $objPHPExcel->getActiveSheet()->getStyle('T1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('T1')->getFill()->getStartColor()->setARGB('00FF0000');
          $objPHPExcel->getActiveSheet()->setCellValue('U1',"税率");
        $objPHPExcel->getActiveSheet()->getStyle('U1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('U1')->getFill()->getStartColor()->setARGB('00FF0000');
          $objPHPExcel->getActiveSheet()->setCellValue('v1',"含税费用额");
        $objPHPExcel->getActiveSheet()->getStyle('V1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('V1')->getFill()->getStartColor()->setARGB('0099CCFF');
          $objPHPExcel->getActiveSheet()->setCellValue('W1',"实际费用额");
        $objPHPExcel->getActiveSheet()->getStyle('W1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('W1')->getFill()->getStartColor()->setARGB('0099CCFF');
          $objPHPExcel->getActiveSheet()->setCellValue('X1',"预计销量");
        $objPHPExcel->getActiveSheet()->getStyle('X1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('X1')->getFill()->getStartColor()->setARGB('00FF0000');
          $objPHPExcel->getActiveSheet()->setCellValue('Y1',"基准销量");
        $objPHPExcel->getActiveSheet()->getStyle('Y1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('Y1')->getFill()->getStartColor()->setARGB('00FF0000');
          $objPHPExcel->getActiveSheet()->setCellValue('Z1',"费用支付方式");
        $objPHPExcel->getActiveSheet()->getStyle('Z1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('Z1')->getFill()->getStartColor()->setARGB('00FF0000');
         $objPHPExcel->getActiveSheet()->setCellValue('AA1',"备注");
        $objPHPExcel->getActiveSheet()->getStyle('AA1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('AA1')->getFill()->getStartColor()->setARGB('0099CCFF');


        $objPHPExcel->getActiveSheet()->setCellValue('A2',"必填项。");
        $objPHPExcel->getActiveSheet()->setCellValue('B2',"必填项。必须是销路通中已存在的供应商编号。");
        $objPHPExcel->getActiveSheet()->setCellValue('C2',"填写供应商编号对应的供应商名称。");
        $objPHPExcel->getActiveSheet()->setCellValue('D2',"必填项，必须是销路通中已存在的分区名称。");
        $objPHPExcel->getActiveSheet()->setCellValue('E2',"如果填写，必须是销路通中已存在的省份名称，如果填写了省份则分区必须填写。");
        $objPHPExcel->getActiveSheet()->setCellValue('F2',"如果填写，必须是销路通中已存在的城市名称，如果填写了城市则省份必须填写。");
        $objPHPExcel->getActiveSheet()->setCellValue('G2',"如果填写，必须是销路通中已存在的经销商编号，如果填写了经销商则城市必须填写。");
        $objPHPExcel->getActiveSheet()->setCellValue('H2',"如果填写，必须是销路通中已存在的经销商名称。");
        $objPHPExcel->getActiveSheet()->setCellValue('I2',"如果填写，必须是销路通中已存在的系统编号，如果填写了系统则经销商必须填写。");
        $objPHPExcel->getActiveSheet()->setCellValue('J2',"如果填写，必须是销路通中已存在的系统名称。");
        $objPHPExcel->getActiveSheet()->setCellValue('K2',"如果填写，必须是销路通中已存在的网点编号，如果填写了网点则系统必须填写。");
        $objPHPExcel->getActiveSheet()->setCellValue('L2',"如果填写，必须是销路通中已存在的网点名称。");
        $objPHPExcel->getActiveSheet()->setCellValue('M2',"必填项。必须是销路通中已存在的品牌名称。");
        $objPHPExcel->getActiveSheet()->setCellValue('N2',"如果填写，必须是销路通中已存在的品类名称。");
        $objPHPExcel->getActiveSheet()->setCellValue('O2',"如果填写，必须是销路通中已存在的系列名称，如果填写了系列，则品类必须填写。");
        $objPHPExcel->getActiveSheet()->setCellValue('P2',"必填项。日期格式：年/月/日");
        $objPHPExcel->getActiveSheet()->setCellValue('Q2',"必填项。截止时间必须大于或等于活动开始时间。日期格式：年/月/日");
        $objPHPExcel->getActiveSheet()->setCellValue('R2',"必填项。必须是销路通系统中已存在的三级费用科目，三级费用科目必须属于市场费用。");
        $objPHPExcel->getActiveSheet()->setCellValue('S2',"必填项。");
        $objPHPExcel->getActiveSheet()->setCellValue('T2',"必填项。只能填写“是” 或者“否”");
        $objPHPExcel->getActiveSheet()->setCellValue('U2',"必填项。只能填写0-1之间的小数。例如：0.17");
        $objPHPExcel->getActiveSheet()->setCellValue('V2',"可不填，填写的值仅作为参考，系统不以填写的值为依据。系统将自动计算。");
        $objPHPExcel->getActiveSheet()->setCellValue('W2',"可不填，填入的值仅作为参考，系统不以填写的值为依据。系统将自动计算。");
        $objPHPExcel->getActiveSheet()->setCellValue('X2',"必填项。");
        $objPHPExcel->getActiveSheet()->setCellValue('Y2',"必填项。");
        $objPHPExcel->getActiveSheet()->setCellValue('Z2',"必填项。必须是销路通系统中已存在的费用支付方式。");
        $objPHPExcel->getActiveSheet()->setCellValue('AA2',"");
       
        #内容
        $h=2;
        for($i=0;$i<count($applyde);$i++){
        	$h++;$vo=$applyde[$i];
        	$objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setWrapText(true);
        	  //水平剧中
	        $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
	        //垂直剧中
	        $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

	        $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,$vo["description"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('B'.$h,$vo["gys_no"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('C'.$h,$vo["gys_name"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('D'.$h,$vo["fenqu"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('E'.$h,$vo["sheng"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('F'.$h,$vo["shi"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('G'.$h,$vo["jsn"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('H'.$h,$vo["jxs"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('I'.$h,$vo["ssn"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('J'.$h,$vo["system"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('K'.$h,$vo["nsn"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('L'.$h,$vo["net"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('M'.$h,$vo["brand"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('N'.$h,$vo["category"]);
	        $objPHPExcel->getActiveSheet()->setCellValue('O'.$h,$vo["series"]);
	        $str=date("Y/M/D",strtotime($vo["start_time"]));
	        $objPHPExcel->getActiveSheet()->setCellValueExplicit('P'.$h,$vo["start_time"],PHPExcel_Cell_DataType::TYPE_STRING);
	        $str=date("Y/M/D",strtotime($vo["end_time"]));
	       $objPHPExcel->getActiveSheet()->setCellValueExplicit('Q'.$h,$vo["end_time"],PHPExcel_Cell_DataType::TYPE_STRING);
	        $objPHPExcel->getActiveSheet()->setCellValue('R'.$h,$vo["kemu3"]);
	        if($vo["pifuzonge"])
	        	$objPHPExcel->getActiveSheet()->setCellValue('S'.$h,round($vo["pifuzonge"],2));
	    	else
	    		$objPHPExcel->getActiveSheet()->setCellValue('S'.$h,round($vo["zonge"],2));
	    	if($vo["dikou"])
	    		$objPHPExcel->getActiveSheet()->setCellValue('T'.$h,"是");
	    	else
	    		$objPHPExcel->getActiveSheet()->setCellValue('T'.$h,"否");
	    	$objPHPExcel->getActiveSheet()->setCellValue('U'.$h,round($vo["shuilv"]/100,2));
	    	if($vo["pifuzonge"])
	        	$objPHPExcel->getActiveSheet()->setCellValue('V'.$h,round(($vo["pifuzonge"]+$vo["pifuzonge"]*$vo["shuilv"]/100),2));
	    	else
	    		$objPHPExcel->getActiveSheet()->setCellValue('V'.$h,round(($vo["zonge"]+$vo["zonge"]*$vo["shuilv"]/100),2));
	    	if($vo["pifuzonge"])
	        	$objPHPExcel->getActiveSheet()->setCellValue('W'.$h,round(($vo["pifuzonge"]+$vo["pifuzonge"]*$vo["shuilv"]/100),2));
	    	else
	    		$objPHPExcel->getActiveSheet()->setCellValue('W'.$h,round(($vo["zonge"]+$vo["zonge"]*$vo["shuilv"]/100),2));
	    	$objPHPExcel->getActiveSheet()->setCellValue('X'.$h,round($vo["zong_xiaoliang"],2));
	    	$objPHPExcel->getActiveSheet()->setCellValue('Y'.$h,round($vo["jizhun_xiaoliang"],2));
	    	 $objPHPExcel->getActiveSheet()->setCellValue('Z'.$h,$vo["zffs"]);
	    	  $objPHPExcel->getActiveSheet()->setCellValue('AA'.$h,$vo["remark"]);
        }

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(40);
             $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
             $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);
             $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(30);
             $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(30);
             $objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(30);
             $objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(30);
             $objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(30);
             $objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('V')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('W')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('X')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('Y')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('Z')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AA')->setWidth(30);




        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
           ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=AP费用明细数据.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        
        $objWriter->save('php://output');
	}

	public function wanzheng($aid){
		//echo 1;exit;
			$apply=Db::table("ap_apply")->alias("ap")
    	->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
    	->join("ap_apply next","ap.next_id=next.id","LEFT")
    	->join("ti_state s","ap.state=s.id")
    	 ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
    	->where(["ap.id"=>$aid,"de.index"=>1])
    	->field("ap.title,ap.no,yuan.no as yuanno,next.no as nextno,yuan.id as yuanid,next.id as nextid,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.created_on,yuan.tag as yuantag,ap.tag as nowtag,ap.tag,ap.is_shengxiao,ap.is_fankui,ap.is_hexiao,ap.is_actived")
    	->find();
    	$applyde=Db::table("ap_apply")->alias("ap")
            ->join("ap_apply_detail apd","apd.apply_id=ap.id")
            ->join("ap_apply_detail yuanapd","apd.yuanmingxi=yuanapd.id","LEFT")
            ->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
            ->join("cg_market_provice p","apd.sheng=p.id","LEFT")
            ->join("cg_market_city c","apd.shi=c.id","LEFT")
            ->join("cg_jxs j","apd.jxs=j.id","LEFT")
            ->join("cg_system s","apd.system=s.id","LEFT")
            ->join("cg_net n","apd.net=n.id","LEFT")
            ->join("pro_brands pb","apd.brand=pb.id","LEFT")
            ->join("pro_category pc","apd.category=pc.id","LEFT")
            ->join("pro_series ps","apd.series=ps.id","LEFT")
            ->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
            ->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
            ->join("gys g","apd.gys=g.id")
            ->join("cg_paymethod cp","apd.zfid=cp.id")
            ->where(["ap.id"=>$aid,"apd.is_deleted"=>0])
            ->field("apd.id,apd.detail_no,apd.is_bu,g.no as gys_no,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.start_time,apd.end_time,k2.title as kemu2,apd.zonge,apd.pifuzonge,apd.shuilv,apd.dikou,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,(apd.zonge+apd.zonge*apd.shuilv/100) as aphanshui,cp.title as zffs,apd.zong_xiaoliang,apd.jizhun_xiaoliang,(apd.zong_xiaoliang-apd.jizhun_xiaoliang) as xinxiaoliang,apd.description,apd.remark,apd.tag,ap.no,yuanapd.start_time as yuanstart,yuanapd.end_time as yuanend,yuanapd.hexiao_time as yuanhexiao,apd.biandongyuanyin,apd.hexiao_time,apd.hexiao,apd.fankuixiaoliang,apd.yujiroi,apd.yujifeiyonglv")
            ->select();
            // print_r($applyde);exit;
    		$contfenqu=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct fenqu");
    	$contbrand=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct brand");
    	$contgys=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct gys");
    	$feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge,sum(apd.zong_xiaoliang) as xiaoliangs from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid  group by k3.id,k3.title");
    	$contfeiyong=count($feiyongs);
    	$contzonge=0;$contzongxiao=0;
    	for($i=0;$i<count($feiyongs);$i++){
    		$contzonge+=$feiyongs[$i]["kezonge"];
    		$contzongxiao+=$feiyongs[$i]["xiaoliangs"];
    	}
    	$contzonge=round($contzonge,2);
    	$contzongxiao=round($contzongxiao,2);

    		$eid=Session::get("employee_id");
    		$users=Db::table("employee")->where(["id"=>$eid])->find();


    		  Vendor("PHPExcel");
        
        
       Vendor("PHPExcel.Writer.Excel5");

       // Loader::import('PHPExcel.Classes.PHPExcel');
        //Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
       //  Vendor("Excel.PHPExcel.Writer.Excel2007");
        $objPHPExcel= new PHPExcel();
            
            
        $objProps=$objPHPExcel->getProperties();
            
        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");
            	
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("AP费用申请");
        #标题
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('3')->setRowHeight(20);

        $objPHPExcel->getActiveSheet()->mergeCells('A1:AK1');
        $objPHPExcel->getActiveSheet()->setCellValue('A1',$apply["title"]."  费用申请单");
              //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(14);

          #################表头信息
        $objPHPExcel->getActiveSheet()->mergeCells('A2:AK2');
        $objPHPExcel->getActiveSheet()->setCellValue('A2',"(本表单由软件导出，导出时间：".date("Y-m-d H:i:s")."；导出人：{$users["em_name"]})");
                //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);

         #################申请标题
        $objPHPExcel->getActiveSheet()->mergeCells('A3:AK3');
        $objPHPExcel->getActiveSheet()->setCellValue('A3',$apply["title"]);
      	//垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setSize(11);

        #单据信息
         $objPHPExcel->getActiveSheet()->setCellValue('A4',"编号");
         $objPHPExcel->getActiveSheet()->setCellValueExplicit('B4',$apply["no"],PHPExcel_Cell_DataType::TYPE_STRING);

         $objPHPExcel->getActiveSheet()->setCellValue('C4',"原申请批复编号");
        if($apply["yuanno"])
        $objPHPExcel->getActiveSheet()->setCellValueExplicit('D4',$apply["yuanno"],PHPExcel_Cell_DataType::TYPE_STRING);
    	else
    	$objPHPExcel->getActiveSheet()->setCellValue('D4',"无");
       
        $objPHPExcel->getActiveSheet()->setCellValue('E4',"修改后编号");
        if($apply["nextno"])
        $objPHPExcel->getActiveSheet()->setCellValueExplicit('F4',$apply["nextno"],PHPExcel_Cell_DataType::TYPE_STRING);
    	else
    	$objPHPExcel->getActiveSheet()->setCellValue('F4',"无");

    	 $objPHPExcel->getActiveSheet()->setCellValue('G4',"申请时间");
        $objPHPExcel->getActiveSheet()->setCellValueExplicit('H4',$apply["created_on"],PHPExcel_Cell_DataType::TYPE_STRING);
       
        $objPHPExcel->getActiveSheet()->setCellValue('I4',"申请人");
        $objPHPExcel->getActiveSheet()->setCellValue('J4',$apply["cname"]."({$apply["job_name"]})");
       
        $objPHPExcel->getActiveSheet()->setCellValue('K4',"申请人部门");
        $objPHPExcel->getActiveSheet()->setCellValue('L4',$apply["de_name"]);
       
        $objPHPExcel->getActiveSheet()->setCellValue('M4',"状态");
        $zt=$apply["zhuangtai"];$fzt="";
        if($apply["tag"]==1){
        	$fzt="已异动";
        }else if($apply["tag"]==2){
        	$fzt="已取消";
        }else if($apply["is_actived"]==1){
        	$fzt="正常";
        }else{
        	$fzt="取消";
        }
         $objPHPExcel->getActiveSheet()->setCellValue('N4',"{$zt}/{$fzt}");
          $objPHPExcel->getActiveSheet()->getStyle('4')->getAlignment()->setWrapText(true);
           //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('4')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('4')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

           //填充背景色
        $objPHPExcel->getActiveSheet()->getStyle('A4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('C4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('C4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('E4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('E4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('G4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('G4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('I4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('I4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('K4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('K4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('M4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('M4')->getFill()->getStartColor()->setARGB('0099CCFF');
        #标题
        $objPHPExcel->getActiveSheet()->getStyle('6')->getAlignment()->setWrapText(true);
       	$objPHPExcel->getActiveSheet()->getRowDimension('6')->setRowHeight(20);
       	$objPHPExcel->getActiveSheet()->getStyle('7')->getAlignment()->setWrapText(true);
       	$objPHPExcel->getActiveSheet()->getRowDimension('7')->setRowHeight(40);
       	 $objPHPExcel->getActiveSheet()->getStyle('A6:AK6')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A6:AK6')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('A7:AK7')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A7:AK7')->getFill()->getStartColor()->setARGB('0099CCFF');
         //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('6')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('6')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

 //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('7')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('7')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        $objPHPExcel->getActiveSheet()->setCellValue('A6',"状态");
        $objPHPExcel->getActiveSheet()->mergeCells('A6:A7');
         $objPHPExcel->getActiveSheet()->setCellValue('B6',"审批人");
        $objPHPExcel->getActiveSheet()->mergeCells('B6:B7');
         $objPHPExcel->getActiveSheet()->setCellValue('C6',"NO");
        $objPHPExcel->getActiveSheet()->mergeCells('C6:C7');
          $objPHPExcel->getActiveSheet()->setCellValue('D6',"明细编号");
        $objPHPExcel->getActiveSheet()->mergeCells('D6:D7');
          $objPHPExcel->getActiveSheet()->setCellValue('E6',"供货商信息");
        $objPHPExcel->getActiveSheet()->mergeCells('E6:F6');
         $objPHPExcel->getActiveSheet()->setCellValue('E7',"供货商编码");
          $objPHPExcel->getActiveSheet()->setCellValue('F7',"供货商名称");
           $objPHPExcel->getActiveSheet()->setCellValue('G6',"活动信息详情");
        $objPHPExcel->getActiveSheet()->mergeCells('G6:T6');
         $objPHPExcel->getActiveSheet()->setCellValue('G7',"分区");
          $objPHPExcel->getActiveSheet()->setCellValue('H7',"省份");
         $objPHPExcel->getActiveSheet()->setCellValue('I7',"城市");
         $objPHPExcel->getActiveSheet()->setCellValue('J7',"经销商");
         $objPHPExcel->getActiveSheet()->setCellValue('K7',"系统");
         $objPHPExcel->getActiveSheet()->setCellValue('L7',"网点");
         $objPHPExcel->getActiveSheet()->setCellValue('M7',"品牌");
         $objPHPExcel->getActiveSheet()->setCellValue('N7',"品类");
         $objPHPExcel->getActiveSheet()->setCellValue('O7',"系列");
         $objPHPExcel->getActiveSheet()->setCellValue('P7',"原活动执行时间");
         $objPHPExcel->getActiveSheet()->setCellValue('Q7',"异动后活动执行时间");
         $objPHPExcel->getActiveSheet()->setCellValue('R7',"异动原因");
         $objPHPExcel->getActiveSheet()->setCellValue('S7',"取消原因");
         $objPHPExcel->getActiveSheet()->setCellValue('T7',"已核销金额");
          $objPHPExcel->getActiveSheet()->setCellValue('U6',"活动信息详情");
        $objPHPExcel->getActiveSheet()->mergeCells('U6:AI6');
         $objPHPExcel->getActiveSheet()->setCellValue('U7',"二级费用科目");
         $objPHPExcel->getActiveSheet()->setCellValue('V7',"三级费用科目");
         $objPHPExcel->getActiveSheet()->setCellValue('W7',"未税费用金额(元)(申请金额/批复金额)");
         $objPHPExcel->getActiveSheet()->setCellValue('X7',"税率");
         $objPHPExcel->getActiveSheet()->setCellValue('Y7',"是否增值税可抵扣");
        $objPHPExcel->getActiveSheet()->setCellValue('Z7',"含税费用金额(元)");
         $objPHPExcel->getActiveSheet()->setCellValue('AA7',"实际投入费用(元)");
         $objPHPExcel->getActiveSheet()->setCellValue('AB7',"费用支付方式");
         $objPHPExcel->getActiveSheet()->setCellValue('AC7',"预计销量(元)");
         $objPHPExcel->getActiveSheet()->setCellValue('AD7',"预计费用率");
         $objPHPExcel->getActiveSheet()->setCellValue('AE7',"实际销量(元)");
         $objPHPExcel->getActiveSheet()->setCellValue('AF7',"2SR基准销量(元)");
         $objPHPExcel->getActiveSheet()->setCellValue('AG7',"基准销量(元)");
         $objPHPExcel->getActiveSheet()->setCellValue('AH7',"新增销量(元)");
         $objPHPExcel->getActiveSheet()->setCellValue('AI7',"预计ROI");
         $objPHPExcel->getActiveSheet()->setCellValue('AJ6',"项目描述");
        $objPHPExcel->getActiveSheet()->mergeCells('AJ6:AJ7');
        $objPHPExcel->getActiveSheet()->setCellValue('AK6',"备注");
        $objPHPExcel->getActiveSheet()->mergeCells('AK6:AK7');
        $h=0;
        for($i=0;$i<count($applyde);$i++){
        	$h=$i+8;$vo=$applyde[$i];
        	$objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setWrapText(true);
        	  //水平剧中
	        $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
	        //垂直剧中
	        $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
	        switch ($vo["tag"]) {
        		case 0:
        			$objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"正常");
        			break;
        		case 1:
        			$objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"异动");
        			break;
        		case 2:
        			$objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"取消");
        			break;
        	}
        	$objPHPExcel->getActiveSheet()->setCellValue('B'.$h,"无");
        	$objPHPExcel->getActiveSheet()->setCellValue('C'.$h,$i);
        	$objPHPExcel->getActiveSheet()->setCellValue('D'.$h,$vo["no"].'_'.$vo["detail_no"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('E'.$h,$vo["gys_no"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('F'.$h,$vo["gys_name"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('G'.$h,$vo["fenqu"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('H'.$h,$vo["sheng"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('I'.$h,$vo["shi"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('J'.$h,$vo["jxs"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('K'.$h,$vo["system"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('L'.$h,$vo["net"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('M'.$h,$vo["brand"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('N'.$h,$vo["category"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('O'.$h,$vo["series"]);
        	if($vo["tag"]==1){
        		$objPHPExcel->getActiveSheet()->setCellValue('P'.$h,$vo["yuanstart"]."\n".$vo["yuanend"]);
        		$objPHPExcel->getActiveSheet()->setCellValue('Q'.$h,$vo["start_time"]."\n".$vo["end_time"]);
        	}else{
        		$objPHPExcel->getActiveSheet()->setCellValue('P'.$h,$vo["start_time"]."\n".$vo["end_time"]);
        		$objPHPExcel->getActiveSheet()->setCellValue('Q'.$h,"");
        	}
        	if($vo["tag"]==1){
        		$objPHPExcel->getActiveSheet()->setCellValue('R'.$h,$vo["biandongyuanyin"]);
        		$objPHPExcel->getActiveSheet()->setCellValue('S'.$h,"");
        	}else{
        		$objPHPExcel->getActiveSheet()->setCellValue('S'.$h,$vo["biandongyuanyin"]);
        		$objPHPExcel->getActiveSheet()->setCellValue('R'.$h,"");
        	}
        	if($vo["hexiao"])
        		$objPHPExcel->getActiveSheet()->setCellValue('T'.$h,round($vo["hexiao"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('U'.$h,$vo["kemu2"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('V'.$h,$vo["kemu3"]);
        	if($vo["pifuzonge"])
        		$objPHPExcel->getActiveSheet()->setCellValue('W'.$h,round($vo["zonge"],2).'/'.round($vo["pifuzonge"],2));
        	else
        		$objPHPExcel->getActiveSheet()->setCellValue('W'.$h,round($vo["zonge"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('X'.$h,round($vo["shuilv"],2).'%');
        	if($vo["dikou"])
        		$objPHPExcel->getActiveSheet()->setCellValue('Y'.$h,"是");
        	else
        		$objPHPExcel->getActiveSheet()->setCellValue('Y'.$h,"否");
        	if($vo["hanshui"])
        		$objPHPExcel->getActiveSheet()->setCellValue('Z'.$h,round($vo["hanshui"],2));
        	if($vo["hanshui"])
        		$objPHPExcel->getActiveSheet()->setCellValue('AA'.$h,round($vo["hanshui"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('AB'.$h,$vo["zffs"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('AC'.$h,round($vo["zong_xiaoliang"],2));
            $objPHPExcel->getActiveSheet()->setCellValue('AD'.$h,round($vo["yujifeiyonglv"],2).'%');
        	if($vo["fankuixiaoliang"])
        		$objPHPExcel->getActiveSheet()->setCellValue('AE'.$h,round($vo["fankuixiaoliang"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('AG'.$h,round($vo["jizhun_xiaoliang"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('AH'.$h,round($vo["xinxiaoliang"],2));
            $objPHPExcel->getActiveSheet()->setCellValue('AI'.$h,round($vo["yujiroi"],2).'%');
        	$objPHPExcel->getActiveSheet()->setCellValue('AJ'.$h,$vo["description"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('AK'.$h,$vo["remark"]);
        }
        #总计
        $all=Db::table("ap_apply_detail")->query("select sum(hexiao) as hexiaos,sum(zonge) as zonges,sum(pifuzonge) as pifuzonges,sum(pifuzonge+pifuzonge*shuilv/100) as hanshuis,sum(zonge+zonge*shuilv/100) as aphanshuis,sum(zong_xiaoliang) as zong_xiaoliangs,sum(jizhun_xiaoliang) as jizhun_xiaoliangs,sum(fankuixiaoliang) as fankuixiaoliangs,sum(zong_xiaoliang-jizhun_xiaoliang) as xinxiaoliangs from ap_apply_detail where apply_id=$aid and is_deleted=0");
         $all[0]["yujifeiyonglvs"]=$all[0]["hanshuis"]/$all[0]["zong_xiaoliangs"]*100;
            $all[0]["yujirois"]=0;
            for($i=0;$i<count($applyde);$i++){
                $all[0]["yujirois"]+=($applyde[$i]["yujiroi"]*$applyde[$i]["aphanshui"]);
            }
            $all[0]["yujirois"]=$all[0]["yujirois"]/$all[0]["aphanshuis"];

        $zongji=$all[0];
        $h++;
         $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"总计");
        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:J{$h}");
         //水平剧中
	        $objPHPExcel->getActiveSheet()->getStyle('A'.$h)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
	        if($zongji["hexiaos"])
	         $objPHPExcel->getActiveSheet()->setCellValue('T'.$h,round($zongji["hexiaos"],2));
	     	if($zongji["pifuzonges"])
	         $objPHPExcel->getActiveSheet()->setCellValue('W'.$h,round($zongji["pifuzonges"],2));
	     if($zongji["hanshuis"])
	     	$objPHPExcel->getActiveSheet()->setCellValue('Z'.$h,round($zongji["hanshuis"],2));
	     if($zongji["hanshuis"])
	     	$objPHPExcel->getActiveSheet()->setCellValue('AA'.$h,round($zongji["hanshuis"],2));
	     $objPHPExcel->getActiveSheet()->setCellValue('AC'.$h,round($zongji["zong_xiaoliangs"],2));
         $objPHPExcel->getActiveSheet()->setCellValue('AD'.$h,round($zongji["yujifeiyonglvs"],2)."%");
	     if($zongji["fankuixiaoliangs"])
	     	$objPHPExcel->getActiveSheet()->setCellValue('AE'.$h,round($zongji["fankuixiaoliangs"],2));
	     $objPHPExcel->getActiveSheet()->setCellValue('AG'.$h,round($zongji["jizhun_xiaoliangs"],2));
         $objPHPExcel->getActiveSheet()->setCellValue('AI'.$h,round($zongji["yujirois"],2)."%");
	     $objPHPExcel->getActiveSheet()->setCellValue('AH'.$h,round($zongji["xinxiaoliangs"],2));

	     $h+=2;
	     #归纳
	     $str="本申请中包含{$contfenqu}个分区，{$contbrand}个品牌,{$contgys}个供应商,{$contfeiyong}个三级费用科目  其中";
	     for($i=0;$i<count($feiyongs);$i++){
	     	$str.="{$feiyongs[$i]["title"]}:".round($feiyongs[$i]["kezonge"],2)."(元)  ";
	     }
	     $str.="总预计未税费用:".round($contzonge,2)."  （元）      总预计销售量：".round($contzongxiao,2)."（元）";
	     $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,$str);
        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:AK{$h}");
			$h+=2;
			 $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"审批意见");
        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:AK{$h}");
         $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->getStartColor()->setARGB('0099CCFF');
         if($apply["is_actived"]==1){
                 if($apply["yuanid"])
                     $logs=$this->getlog(13,$aid);
                 else
                    $logs=$this->getlog(11,$aid);
            }else{

                $logs=$this->getlog(12,$aid);
            }
        //print_r($logs);
        //$this->assign("logs",$logs);
        for($i=0;$i<count($logs);$i++){
            $h++;
            if($logs[$i]["COMMENTS"])
                $str="{$logs[$i]["USERNAME"]} 审批动作：{$logs[$i]["MEMO"]}；审批意见：{$logs[$i]["COMMENTS"]}(审批时间：{$logs[$i]["ACTIONTIME"]})";
            else
                $str="{$logs[$i]["USERNAME"]} 审批动作：{$logs[$i]["MEMO"]}；审批意见：无 (审批时间：{$logs[$i]["ACTIONTIME"]})";
             $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,$str);
            $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:AK{$h}");
        }
             $styleArray = array(  
        'borders' => array(  
            'allborders' => array(  
                //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框  
                //'color' => array('argb' => 'FFFF0000'),  
            ),  
        ),  
    );  
   $objPHPExcel->getActiveSheet()->getStyle('A1:AK'.$h)->applyFromArray($styleArray);//这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪
        
         $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
             $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
             $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(25);
            $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);
             $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(40);
             $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(20);
             $objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(20);
             $objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(20);
             $objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(20);
             $objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('V')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('W')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('X')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('Y')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('Z')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AA')->setWidth(15);
           $objPHPExcel->getActiveSheet()->getColumnDimension('AB')->setWidth(15);
           $objPHPExcel->getActiveSheet()->getColumnDimension('AC')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AD')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AE')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AF')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AG')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AH')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AI')->setWidth(15);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AJ')->setWidth(60);
            $objPHPExcel->getActiveSheet()->getColumnDimension('AK')->setWidth(50);



$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
           ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=AP费用明细完整版.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        
        $objWriter->save('php://output');


	}
    public function shenpisave(){
        $request = Request::instance();
        $data=$request->post();

        // print_r($data);exit;
        try{
           for($i=0;$i<count($data["did"]);$i++){
                $shuilv=Db::table("ap_apply_detail")->where(["id"=>$data["did"][$i]])->value("shuilv");
                $up["id"]=$data["did"][$i];
                $up["isok"]=$data["de"]["isok"][$up["id"]];
                $up["pifuzonge"]=$data["de"]["pifuzonge"][$up["id"]];
                Db::table("ap_apply_detail")->update($up);
                //print_r($up);exit;
                $yusuans=db::table("yusuan")->alias("y")->join("yusuan_detail yd","y.id=yd.yid")->where(["y.type"=>2,"did"=>$up["id"]])
                ->field("yd.id,yd.tianshu,yd.zongtianshu")->select();

                for($j=0;$j<count($yusuans);$j++){
                    $upy["id"]=$yusuans[$j]["id"];
                    $upy['jine']=($up["pifuzonge"]+$up["pifuzonge"]*$shuilv/100)/$yusuans[$j]["zongtianshu"]*$yusuans[$j]["tianshu"];
                    Db::table("yusuan_detail")->update($upy);
                }
            } 
        }catch (\Exception $e){
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
        return json_encode(["msg"=>"","state"=>1]);
    }
    //审核页面
    public function shenhe($myId,$trackId,$workId){
        $workfloawde=Db::table("cg_workflow")->where(["id"=>$myId])->find();
        $aid=$workfloawde["yw_id"];
        $state=Db::table("ap_apply")->where(["id"=>$aid])->value("state");
        if($state==2){
            //打回
            $this->redirect('Apapply/addform', ['aid' => $aid,"from"=>2]);
        }else{

            $apply=Db::table("ap_apply")->alias("ap")
            ->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
            ->join("ap_apply next","ap.next_id=next.id","LEFT")
            ->join("ti_state s","ap.state=s.id")
             ->join("users uc","ap.c_users_id=uc.id","LEFT")
            ->join("employee ec","uc.employee_id=ec.id","LEFT")
            ->join("job_employee je","ec.id=je.employee_id","LEFT")
            ->join("job j","je.job_id=j.id","LEFT")
            ->join("department_employee de","ec.id=de.employee_id","LEFT")
            ->join("department d","de.department_id=d.id","LEFT")
            ->where(["ap.id"=>$aid,"de.index"=>1])
            ->field("ap.title,ap.no,yuan.no as yuanno,next.no as nextno,yuan.id as yuanid,next.id as nextid,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.created_on,yuan.tag as yuantag,ap.tag as nowtag,ap.tag,ap.is_shengxiao,ap.is_fankui,ap.is_hexiao,ap.annex_id")
            ->find();
            $this->assign("apply",$apply);
            $fujian=[];
                //print_r($apply);
                if($apply["annex_id"]){
                    $fujian=Db::table("annex")->where("id in ({$apply["annex_id"]})")->select();
                    //print_r($fujian);
                }
            $this->assign("fujian",$fujian);
            $this->assign("aid",$aid);
                $applyde=Db::table("ap_apply")->alias("ap")
                ->join("ap_apply_detail apd","apd.apply_id=ap.id")
                ->join("ap_apply_detail yuanapd","apd.yuanmingxi=yuanapd.id","LEFT")
                ->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
                ->join("cg_market_provice p","apd.sheng=p.id","LEFT")
                ->join("cg_market_city c","apd.shi=c.id","LEFT")
                ->join("cg_jxs j","apd.jxs=j.id","LEFT")
                ->join("cg_system s","apd.system=s.id","LEFT")
                ->join("cg_net n","apd.net=n.id","LEFT")
                ->join("pro_brands pb","apd.brand=pb.id","LEFT")
                ->join("pro_category pc","apd.category=pc.id","LEFT")
                ->join("pro_series ps","apd.series=ps.id","LEFT")
                ->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
                ->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
                ->join("gys g","apd.gys=g.id")
                ->join("cg_paymethod cp","apd.zfid=cp.id")
                ->where(["ap.id"=>$aid,"apd.is_deleted"=>0])
                ->field("apd.id,apd.detail_no,apd.is_bu,g.no as gys_no,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.start_time,apd.end_time,k2.title as kemu2,apd.zonge,apd.pifuzonge,apd.shuilv,apd.dikou,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,(apd.zonge+apd.zonge*apd.shuilv/100) as aphanshui,cp.title as zffs,apd.zong_xiaoliang,apd.jizhun_xiaoliang,(apd.zong_xiaoliang-apd.jizhun_xiaoliang) as xinxiaoliang,apd.description,apd.remark,apd.tag,ap.no,yuanapd.start_time as yuanstart,yuanapd.end_time as yuanend,yuanapd.hexiao_time as yuanhexiao,apd.biandongyuanyin,apd.hexiao_time,apd.hexiao,apd.fankuixiaoliang,apd.yujiroi,apd.yujifeiyonglv,apd.isok")
                ->select();
            $this->assign("applyde",$applyde);
                $contfenqu=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct fenqu");
            $contbrand=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct brand");
            $contgys=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct gys");
            $feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge,sum(apd.zong_xiaoliang) as xiaoliangs from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid  group by k3.id,k3.title");
            $this->assign("contfenqu",$contfenqu);
            $this->assign("contbrand",$contbrand);
            $this->assign("contgys",$contgys);
            $this->assign("feiyongs",$feiyongs);
            $contfeiyong=count($feiyongs);
            $this->assign("contfeiyong",$contfeiyong);
            $contzonge=0;$contzongxiao=0;
            for($i=0;$i<count($feiyongs);$i++){
                $contzonge+=$feiyongs[$i]["kezonge"];
                $contzongxiao+=$feiyongs[$i]["xiaoliangs"];
            }
            $contzonge=round($contzonge,2);
            $contzongxiao=round($contzongxiao,2);
            $this->assign("contzonge",$contzonge);
            $this->assign("contzongxiao",$contzongxiao);

            $all=Db::table("ap_apply_detail")->query("select sum(hexiao) as hexiaos,sum(zonge) as zonges,sum(pifuzonge) as pifuzonges,sum(pifuzonge+pifuzonge*shuilv/100) as hanshuis,sum(zonge+zonge*shuilv/100) as aphanshuis,sum(zong_xiaoliang) as zong_xiaoliangs,sum(jizhun_xiaoliang) as jizhun_xiaoliangs,sum(fankuixiaoliang) as fankuixiaoliangs,sum(zong_xiaoliang-jizhun_xiaoliang) as xinxiaoliangs from ap_apply_detail where apply_id=$aid and is_deleted=0");
             $all[0]["yujifeiyonglvs"]=$all[0]["hanshuis"]/$all[0]["zong_xiaoliangs"]*100;
                $all[0]["yujirois"]=0;
                for($i=0;$i<count($applyde);$i++){
                    $all[0]["yujirois"]+=($applyde[$i]["yujiroi"]*$applyde[$i]["aphanshui"]);
                }
                $all[0]["yujirois"]=$all[0]["yujirois"]/$all[0]["aphanshuis"];
            $this->assign("all",$all);

            //获取反馈列表
            $fk=Db::table("ap_fankui")->alias("fk")
            ->join("ap_apply_detail apd","fk.id=apd.fankui_id")
            ->where("fk.is_actived=1 and fk.is_deleted=0 and fk.state<>0 and apd.is_actived=1 and apd.is_deleted=0 and apd.apply_id=$aid")
            ->group("fk.id")
            ->field("fk.no,fk.id")
            ->select();
            if($fk){
                $hasfk=1;
            }else{
                $hasfk=0;
            }
            $this->assign("fk",$fk);
            $this->assign("hasfk",$hasfk);
            //获取核销列表
            $hx=Db::table("ap_hexiao_apply")->alias("ahp")
            ->join("ap_apply ap","ahp.apply_id=ap.id")
            ->where("ahp.is_deleted=0 and ap.is_deleted=0 and ap.is_actived=1 and ahp.apply_id=$aid and ahp.state<>0")
            ->field("ahp.no,ahp.id")->select();
            if($hx){
                $hashx=1;
            }else{
                $hashx=0;
            }
            $this->assign("hx",$hx);
            $this->assign("hashx",$hashx);
             $logs=$this->getlog(11,$aid);
            //print_r($logs);
            $this->assign("logs",$logs);
            return $this->fetch();
        }
    }
    public function qxshenhe($myId,$trackId,$workId){
        $workfloawde=Db::table("cg_workflow")->where(["id"=>$myId])->find();
        $aid=$workfloawde["yw_id"];
        $aps=$apply=Db::table("ap_apply")->where(["id"=>$aid])->find();
        if($aps["state"]==2){
            if($aps["is_actived"])
                $this->redirect('Apapply/zuofeiyd', ['aid' => $aid,"from"=>2]);
            else
                $this->redirect('Apapply/qxzuofei', ['aid' => $aid,"from"=>2]);
        }else{
            $apply=Db::table("ap_apply")->alias("ap")
            ->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
            ->join("ap_apply next","ap.next_id=next.id","LEFT")
            ->join("ti_state s","ap.state=s.id")
             ->join("users uc","ap.c_users_id=uc.id","LEFT")
            ->join("employee ec","uc.employee_id=ec.id","LEFT")
            ->join("job_employee je","ec.id=je.employee_id","LEFT")
            ->join("job j","je.job_id=j.id","LEFT")
            ->join("department_employee de","ec.id=de.employee_id","LEFT")
            ->join("department d","de.department_id=d.id","LEFT")
            ->where(["ap.id"=>$aid,"de.index"=>1])
            ->field("ap.title,ap.no,yuan.no as yuanno,next.no as nextno,yuan.id as yuanid,next.id as nextid,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.created_on,yuan.tag as yuantag,ap.tag as nowtag,ap.tag,ap.is_shengxiao,ap.is_fankui,ap.is_hexiao,ap.annex_id,ap.state,ap.is_actived")
            ->find();
            $this->assign("apply",$apply);
            $fujian=[];
                //print_r($apply);
                if($apply["annex_id"]){
                    $fujian=Db::table("annex")->where("id in ({$apply["annex_id"]})")->select();
                    //print_r($fujian);
                }
            $this->assign("fujian",$fujian);
            $this->assign("aid",$aid);
                $applyde=Db::table("ap_apply")->alias("ap")
                ->join("ap_apply_detail apd","apd.apply_id=ap.id")
                ->join("ap_apply_detail yuanapd","apd.yuanmingxi=yuanapd.id","LEFT")
                ->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
                ->join("cg_market_provice p","apd.sheng=p.id","LEFT")
                ->join("cg_market_city c","apd.shi=c.id","LEFT")
                ->join("cg_jxs j","apd.jxs=j.id","LEFT")
                ->join("cg_system s","apd.system=s.id","LEFT")
                ->join("cg_net n","apd.net=n.id","LEFT")
                ->join("pro_brands pb","apd.brand=pb.id","LEFT")
                ->join("pro_category pc","apd.category=pc.id","LEFT")
                ->join("pro_series ps","apd.series=ps.id","LEFT")
                ->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
                ->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
                ->join("gys g","apd.gys=g.id")
                ->join("cg_paymethod cp","apd.zfid=cp.id")
                ->where(["ap.id"=>$aid,"apd.is_deleted"=>0])
                ->field("apd.id,apd.detail_no,apd.is_bu,g.no as gys_no,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.start_time,apd.end_time,k2.title as kemu2,apd.zonge,apd.pifuzonge,apd.shuilv,apd.dikou,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,(apd.zonge+apd.zonge*apd.shuilv/100) as aphanshui,cp.title as zffs,apd.zong_xiaoliang,apd.jizhun_xiaoliang,(apd.zong_xiaoliang-apd.jizhun_xiaoliang) as xinxiaoliang,apd.description,apd.remark,apd.tag,ap.no,yuanapd.start_time as yuanstart,yuanapd.end_time as yuanend,yuanapd.hexiao_time as yuanhexiao,apd.biandongyuanyin,apd.hexiao_time,apd.hexiao,apd.fankuixiaoliang,apd.yujiroi,apd.yujifeiyonglv")
                ->select();
            $this->assign("applyde",$applyde);
                $contfenqu=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct fenqu");
            $contbrand=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct brand");
            $contgys=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct gys");
            $feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge,sum(apd.zong_xiaoliang) as xiaoliangs from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid  group by k3.id,k3.title");
            $this->assign("contfenqu",$contfenqu);
            $this->assign("contbrand",$contbrand);
            $this->assign("contgys",$contgys);
            $this->assign("feiyongs",$feiyongs);
            $contfeiyong=count($feiyongs);
            $this->assign("contfeiyong",$contfeiyong);
            $contzonge=0;$contzongxiao=0;
            for($i=0;$i<count($feiyongs);$i++){
                $contzonge+=$feiyongs[$i]["kezonge"];
                $contzongxiao+=$feiyongs[$i]["xiaoliangs"];
            }
            $contzonge=round($contzonge,2);
            $contzongxiao=round($contzongxiao,2);
            $this->assign("contzonge",$contzonge);
            $this->assign("contzongxiao",$contzongxiao);

            $all=Db::table("ap_apply_detail")->query("select sum(hexiao) as hexiaos,sum(zonge) as zonges,sum(pifuzonge) as pifuzonges,sum(pifuzonge+pifuzonge*shuilv/100) as hanshuis,sum(zonge+zonge*shuilv/100) as aphanshuis,sum(zong_xiaoliang) as zong_xiaoliangs,sum(jizhun_xiaoliang) as jizhun_xiaoliangs,sum(fankuixiaoliang) as fankuixiaoliangs,sum(zong_xiaoliang-jizhun_xiaoliang) as xinxiaoliangs from ap_apply_detail where apply_id=$aid and is_deleted=0");
             $all[0]["yujifeiyonglvs"]=$all[0]["hanshuis"]/$all[0]["zong_xiaoliangs"]*100;
                $all[0]["yujirois"]=0;
                for($i=0;$i<count($applyde);$i++){
                    $all[0]["yujirois"]+=($applyde[$i]["yujiroi"]*$applyde[$i]["aphanshui"]);
                }
                $all[0]["yujirois"]=$all[0]["yujirois"]/$all[0]["aphanshuis"];
            $this->assign("all",$all);

            //获取反馈列表
            $fk=Db::table("ap_fankui")->alias("fk")
            ->join("ap_apply_detail apd","fk.id=apd.fankui_id")
            ->where("fk.is_actived=1 and fk.is_deleted=0 and fk.state<>0 and apd.is_actived=1 and apd.is_deleted=0 and apd.apply_id=$aid")
            ->group("fk.id")
            ->field("fk.no,fk.id")
            ->select();
            if($fk){
                $hasfk=1;
            }else{
                $hasfk=0;
            }
            $this->assign("fk",$fk);
            $this->assign("hasfk",$hasfk);
            //获取核销列表
            $hx=Db::table("ap_hexiao_apply")->alias("ahp")
            ->join("ap_apply ap","ahp.apply_id=ap.id")
            ->where("ahp.is_deleted=0 and ap.is_deleted=0 and ap.is_actived=1 and ahp.apply_id=$aid and ahp.state<>0")
            ->field("ahp.no,ahp.id")->select();
            if($hx){
                $hashx=1;
            }else{
                $hashx=0;
            }
            $this->assign("hx",$hx);
            $this->assign("hashx",$hashx);
            if($apply["is_actived"]==1){
                 if($apply["yuanid"])
                     $logs=$this->getlog(13,$aid);
                 else
                    $logs=$this->getlog(11,$aid);
            }else{

                $logs=$this->getlog(12,$aid);
            }
            //print_r($logs);
            $this->assign("logs",$logs);
            return $this->fetch();
        }
        
    }
    //作废异动
    public function zuofeiyd($aid,$from=1){
        $this->assign("from",$from);
            $apply=Db::table("ap_apply")->alias("ap")
        ->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
        ->join("ap_apply next","ap.next_id=next.id","LEFT")
        ->join("ti_state s","ap.state=s.id")
         ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
        ->where(["ap.id"=>$aid,"de.index"=>1])
        ->field("ap.title,ap.no,yuan.no as yuanno,next.no as nextno,yuan.id as yuanid,next.id as nextid,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.created_on,yuan.tag as yuantag,ap.tag as nowtag,ap.tag,ap.is_shengxiao,ap.is_fankui,ap.is_hexiao,ap.annex_id,ap.state,ap.is_actived")
        ->find();
        $this->assign("apply",$apply);
        $fujian=[];
            //print_r($apply);
            if($apply["annex_id"]){
                $fujian=Db::table("annex")->where("id in ({$apply["annex_id"]})")->select();
                //print_r($fujian);
            }
        $this->assign("fujian",$fujian);
        $this->assign("aid",$aid);
            $applyde=Db::table("ap_apply")->alias("ap")
            ->join("ap_apply_detail apd","apd.apply_id=ap.id")
            ->join("ap_apply_detail yuanapd","apd.yuanmingxi=yuanapd.id","LEFT")
            ->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
            ->join("cg_market_provice p","apd.sheng=p.id","LEFT")
            ->join("cg_market_city c","apd.shi=c.id","LEFT")
            ->join("cg_jxs j","apd.jxs=j.id","LEFT")
            ->join("cg_system s","apd.system=s.id","LEFT")
            ->join("cg_net n","apd.net=n.id","LEFT")
            ->join("pro_brands pb","apd.brand=pb.id","LEFT")
            ->join("pro_category pc","apd.category=pc.id","LEFT")
            ->join("pro_series ps","apd.series=ps.id","LEFT")
            ->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
            ->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
            ->join("gys g","apd.gys=g.id")
            ->join("cg_paymethod cp","apd.zfid=cp.id")
            ->where(["ap.id"=>$aid,"apd.is_deleted"=>0])
            ->field("apd.id,apd.detail_no,apd.is_bu,g.no as gys_no,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.start_time,apd.end_time,k2.title as kemu2,apd.zonge,apd.pifuzonge,apd.shuilv,apd.dikou,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,(apd.zonge+apd.zonge*apd.shuilv/100) as aphanshui,cp.title as zffs,apd.zong_xiaoliang,apd.jizhun_xiaoliang,(apd.zong_xiaoliang-apd.jizhun_xiaoliang) as xinxiaoliang,apd.description,apd.remark,apd.tag,ap.no,yuanapd.start_time as yuanstart,yuanapd.end_time as yuanend,yuanapd.hexiao_time as yuanhexiao,apd.biandongyuanyin,apd.hexiao_time,apd.hexiao,apd.fankuixiaoliang,apd.yujiroi,apd.yujifeiyonglv")
            ->select();
            //print_r($apply_de);
        $this->assign("applyde",$applyde);
            $contfenqu=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct fenqu");
        $contbrand=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct brand");
        $contgys=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct gys");
        $feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge,sum(apd.zong_xiaoliang) as xiaoliangs from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid  group by k3.id,k3.title");
        $this->assign("contfenqu",$contfenqu);
        $this->assign("contbrand",$contbrand);
        $this->assign("contgys",$contgys);
        $this->assign("feiyongs",$feiyongs);
        $contfeiyong=count($feiyongs);
        $this->assign("contfeiyong",$contfeiyong);
        $contzonge=0;$contzongxiao=0;
        for($i=0;$i<count($feiyongs);$i++){
            $contzonge+=$feiyongs[$i]["kezonge"];
            $contzongxiao+=$feiyongs[$i]["xiaoliangs"];
        }
        $contzonge=round($contzonge,2);
        $contzongxiao=round($contzongxiao,2);
        $this->assign("contzonge",$contzonge);
        $this->assign("contzongxiao",$contzongxiao);

        $all=Db::table("ap_apply_detail")->query("select sum(hexiao) as hexiaos,sum(zonge) as zonges,sum(pifuzonge) as pifuzonges,sum(pifuzonge+pifuzonge*shuilv/100) as hanshuis,sum(zonge+zonge*shuilv/100) as aphanshuis,sum(zong_xiaoliang) as zong_xiaoliangs,sum(jizhun_xiaoliang) as jizhun_xiaoliangs,sum(fankuixiaoliang) as fankuixiaoliangs,sum(zong_xiaoliang-jizhun_xiaoliang) as xinxiaoliangs from ap_apply_detail where apply_id=$aid and is_deleted=0");
         $all[0]["yujifeiyonglvs"]=$all[0]["hanshuis"]/$all[0]["zong_xiaoliangs"]*100;
            $all[0]["yujirois"]=0;
            for($i=0;$i<count($applyde);$i++){
                $all[0]["yujirois"]+=($applyde[$i]["yujiroi"]*$applyde[$i]["aphanshui"]);
            }
            $all[0]["yujirois"]=$all[0]["yujirois"]/$all[0]["aphanshuis"];
        $this->assign("all",$all);

        //获取反馈列表
        $fk=Db::table("ap_fankui")->alias("fk")
        ->join("ap_apply_detail apd","fk.id=apd.fankui_id")
        ->where("fk.is_actived=1 and fk.is_deleted=0 and fk.state<>0 and apd.is_actived=1 and apd.is_deleted=0 and apd.apply_id=$aid")
        ->group("fk.id")
        ->field("fk.no,fk.id")
        ->select();
        if($fk){
            $hasfk=1;
        }else{
            $hasfk=0;
        }
        $this->assign("fk",$fk);
        $this->assign("hasfk",$hasfk);
        //获取核销列表
        $hx=Db::table("ap_hexiao_apply")->alias("ahp")
        ->join("ap_apply ap","ahp.apply_id=ap.id")
        ->where("ahp.is_deleted=0 and ap.is_deleted=0 and ap.is_actived=1 and ahp.apply_id=$aid and ahp.state<>0")
        ->field("ahp.no,ahp.id")->select();
        if($hx){
            $hashx=1;
        }else{
            $hashx=0;
        }
        $this->assign("hx",$hx);
        $this->assign("hashx",$hashx);
        if($apply["is_actived"]==1){
                 if($apply["yuanid"])
                     $logs=$this->getlog(13,$aid);
                 else
                    $logs=$this->getlog(11,$aid);
            }else{

                $logs=$this->getlog(12,$aid);
            }
        //print_r($logs);
        $this->assign("logs",$logs);
        $btn=$this->getbton(13,$aid);
        $this->assign("btn",$btn);
        return $this->fetch();
    }
	//申请详细
	public function apply_de($aid){

			$apply=Db::table("ap_apply")->alias("ap")
    	->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
    	->join("ap_apply next","ap.next_id=next.id","LEFT")
    	->join("ti_state s","ap.state=s.id")
    	 ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
    	->where(["ap.id"=>$aid,"de.index"=>1])
    	->field("ap.title,ap.no,yuan.no as yuanno,next.no as nextno,yuan.id as yuanid,next.id as nextid,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.created_on,yuan.tag as yuantag,ap.tag as nowtag,ap.tag,ap.is_shengxiao,ap.is_fankui,ap.is_hexiao,ap.annex_id,ap.state,ap.is_actived")
    	->find();
    	$this->assign("apply",$apply);
        $fujian=[];
            //print_r($apply);
            if($apply["annex_id"]){
                $fujian=Db::table("annex")->where("id in ({$apply["annex_id"]})")->select();
                //print_r($fujian);
            }
        $this->assign("fujian",$fujian);
    	$this->assign("aid",$aid);
    		$applyde=Db::table("ap_apply")->alias("ap")
    		->join("ap_apply_detail apd","apd.apply_id=ap.id")
    		->join("ap_apply_detail yuanapd","apd.yuanmingxi=yuanapd.id","LEFT")
    		->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    		->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    		->join("cg_market_city c","apd.shi=c.id","LEFT")
    		->join("cg_jxs j","apd.jxs=j.id","LEFT")
    		->join("cg_system s","apd.system=s.id","LEFT")
    		->join("cg_net n","apd.net=n.id","LEFT")
    		->join("pro_brands pb","apd.brand=pb.id","LEFT")
    		->join("pro_category pc","apd.category=pc.id","LEFT")
    		->join("pro_series ps","apd.series=ps.id","LEFT")
    		->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    		->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    		->join("gys g","apd.gys=g.id")
    		->join("cg_paymethod cp","apd.zfid=cp.id")
    		->where(["ap.id"=>$aid,"apd.is_deleted"=>0])
    		->field("apd.id,apd.detail_no,apd.is_bu,g.no as gys_no,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.start_time,apd.end_time,k2.title as kemu2,apd.zonge,apd.pifuzonge,apd.shuilv,apd.dikou,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,(apd.zonge+apd.zonge*apd.shuilv/100) as aphanshui,cp.title as zffs,apd.zong_xiaoliang,apd.jizhun_xiaoliang,(apd.zong_xiaoliang-apd.jizhun_xiaoliang) as xinxiaoliang,apd.description,apd.remark,apd.tag,ap.no,yuanapd.start_time as yuanstart,yuanapd.end_time as yuanend,yuanapd.hexiao_time as yuanhexiao,apd.biandongyuanyin,apd.hexiao_time,apd.hexiao,apd.fankuixiaoliang,apd.yujiroi,apd.yujifeiyonglv")
    		->select();
            //print_r($apply_de);
		$this->assign("applyde",$applyde);
			$contfenqu=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct fenqu");
    	$contbrand=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct brand");
    	$contgys=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct gys");
    	$feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge,sum(apd.zong_xiaoliang) as xiaoliangs from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid  group by k3.id,k3.title");
    	$this->assign("contfenqu",$contfenqu);
    	$this->assign("contbrand",$contbrand);
    	$this->assign("contgys",$contgys);
    	$this->assign("feiyongs",$feiyongs);
    	$contfeiyong=count($feiyongs);
    	$this->assign("contfeiyong",$contfeiyong);
    	$contzonge=0;$contzongxiao=0;
    	for($i=0;$i<count($feiyongs);$i++){
    		$contzonge+=$feiyongs[$i]["kezonge"];
    		$contzongxiao+=$feiyongs[$i]["xiaoliangs"];
    	}
    	$contzonge=round($contzonge,2);
    	$contzongxiao=round($contzongxiao,2);
		$this->assign("contzonge",$contzonge);
    	$this->assign("contzongxiao",$contzongxiao);

    	$all=Db::table("ap_apply_detail")->query("select sum(hexiao) as hexiaos,sum(zonge) as zonges,sum(pifuzonge) as pifuzonges,sum(pifuzonge+pifuzonge*shuilv/100) as hanshuis,sum(zonge+zonge*shuilv/100) as aphanshuis,sum(zong_xiaoliang) as zong_xiaoliangs,sum(jizhun_xiaoliang) as jizhun_xiaoliangs,sum(fankuixiaoliang) as fankuixiaoliangs,sum(zong_xiaoliang-jizhun_xiaoliang) as xinxiaoliangs from ap_apply_detail where apply_id=$aid and is_deleted=0");
         $all[0]["yujifeiyonglvs"]=$all[0]["hanshuis"]/$all[0]["zong_xiaoliangs"]*100;
            $all[0]["yujirois"]=0;
            for($i=0;$i<count($applyde);$i++){
                $all[0]["yujirois"]+=($applyde[$i]["yujiroi"]*$applyde[$i]["aphanshui"]);
            }
            $all[0]["yujirois"]=$all[0]["yujirois"]/$all[0]["aphanshuis"];
    	$this->assign("all",$all);

    	//获取反馈列表
    	$fk=Db::table("ap_fankui")->alias("fk")
    	->join("ap_apply_detail apd","fk.id=apd.fankui_id")
    	->where("fk.is_actived=1 and fk.is_deleted=0 and fk.state<>8 and fk.state<>9 and apd.is_actived=1 and apd.is_deleted=0 and apd.apply_id=$aid")
    	->group("fk.id")
    	->field("fk.no,fk.id")
    	->select();
    	if($fk){
    		$hasfk=1;
    	}else{
    		$hasfk=0;
    	}
    	$this->assign("fk",$fk);
    	$this->assign("hasfk",$hasfk);
    	//获取核销列表
    	$hx=Db::table("ap_hexiao_apply")->alias("ahp")
    	->join("ap_apply ap","ahp.apply_id=ap.id")
    	->where("ahp.is_deleted=0 and ap.is_deleted=0 and ap.is_actived=1 and ahp.apply_id=$aid and ahp.state<>8 and ahp.state<>9")
    	->field("ahp.no,ahp.id")->select();
    	if($hx){
    		$hashx=1;
    	}else{
    		$hashx=0;
    	}
    	$this->assign("hx",$hx);
    	$this->assign("hashx",$hashx);
        if($apply["is_actived"]==1){
                 if($apply["yuanid"])
                     $logs=$this->getlog(13,$aid);
                 else
                    $logs=$this->getlog(11,$aid);
            }else{

                $logs=$this->getlog(12,$aid);
            }
        //print_r($logs);
        $this->assign("logs",$logs);
		return $this->fetch();
	}
	//审核模拟
	public function shapply($aid){
		$apply=Db::table("ap_apply")->where(["id"=>$aid])->find();
		$yuanid=$apply["yuan_id"];
		$data=["id"=>$aid,"state"=>7,"is_shengxiao"=>1];
		Db::startTrans();
		try{
			Db::table("ap_apply")->update($data);
			if(!$apply["is_actived"]){
				//取消单
				//判断是否整单取消
				$shenyu=Db::table("ap_apply_detail")->where(["is_deleted"=>0,"is_actived"=>1,"apply_id"=>$yuanid])->select();
				//print_r($shenyu);exit;
				if($shenyu){
					//如果有剩余创建新单据
						//生成单号
			    		 $timenow=date("Ymd");
			       		$num=Db::table("ap_apply")->where("no like '$timenow%'")->count();
			      		 $num++;
			      		 $strnum=$timenow.sprintf("%05d", $num);
			      		 //
			      		 
			      		 $newdata=$apply;
			      		 $newdata["no"]=$strnum;$newdata["created_on"]=date("Y-m-d H:i:s");$newdata["is_actived"]=1;$newdata["state"]=7;
			      		 $newdata["yuan_id"]=$yuanid; $newdata["is_shengxiao"]=1;$newdata["tag"]=0;
			      		 unset( $newdata["id"]);
			      		$res=Db::table("ap_apply")->insertGetId($newdata);
			      		//$res=9;
			      		 $dedata=[];
			      		 for($i=0;$i<count($shenyu);$i++){
			      		 	$shenyu[$i]["yuanmingxi"]=$shenyu[$i]["id"];
			      		 	$shenyu[$i]["detail_no"]=$i+1;
			      		 	$shenyu[$i]["apply_id"]=$res;
			      		 	$tmp=$shenyu[$i];
			      		 	unset($tmp["id"]);
			      		 	$dedata[]=$tmp;
			      		 }
			      		 //print_r($dedata);exit;
			      		 Db::table("ap_apply_detail")->insertAll($dedata);
			      		 Db::table("ap_apply")->where(["id"=>$yuanid])->update(["next_id"=>$res,"tag"=>2]);
				}else{
					Db::table("ap_apply")->where(["id"=>$yuanid])->update(["next_id"=>$aid,"tag"=>2]);
				}
			}else{
				//非取消
				//判断是否异动
				if($yuanid){
					Db::table("ap_apply")->where(["id"=>$yuanid])->update(["next_id"=>$aid,"tag"=>1]);
				}
			}
			db::table("ap_apply_detail")->query("update ap_apply_detail set pifuzonge=zonge where apply_id=$aid");
		}catch(\Exception $e){
           
        	Db::rollBack();
            return 2;
        }
        Db::commit();
        return 1;
		
	}
	//列表
	public function index($page=1,$list=20){
		//获取类型列表
    	$states=Db::table("ti_state")->order("paixu")->select();
    	$this->assign("states",$states);
    	$request = Request::instance();
        $eid=Session::get("login_id");
    	
    	$data=$request->post();
    	$where="ap.is_deleted=0 and  apd.is_deleted=0 and ap.c_users_id=$eid ";
    	if($data){
    		if($data["no"])
    			$where.="and ap.no={$data["no"]} ";
    		if(trim($data["title"]))
    			$where.="and ap.title like '%{$data["title"]}%' ";
    		if($data["state"])
    			$where.="and ap.state={$data["state"]} ";
    		if(trim($data["start"]))
    			$where.="and ap.created_on>='{$data["start"]} 00:00:00' ";
    		if(trim($data["end"]))
    			$where.="and ap.created_on<='{$data["end"]} 23:59:59' ";
    	}else{
    		$data=["no"=>"","title"=>"","state"=>"0","start"=>"","end"=>""];
    	}
        $sum=Db::table("ap_apply")->alias("ap")
        ->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
        ->join("ti_state s","ap.state=s.id")
         ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("ap_apply_detail apd","ap.id=apd.apply_id","LEFT")
        ->where($where)
        ->group("ap.id,apd.apply_id")->count();
         $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
    	$applys=Db::table("ap_apply")->alias("ap")
    	->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
    	->join("ti_state s","ap.state=s.id")
    	 ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("ap_apply_detail apd","ap.id=apd.apply_id","LEFT")
    	->where($where)
    	->group("ap.id,apd.apply_id")
    	->order("ap.created_on desc")->limit($start,$list)
    	->field("ap.id,ap.is_actived,ap.no,ap.title,s.title as zhuangtai,ec.em_name as cname,ap.created_on,ap.state,ap.yuan_id,ap.next_id,ap.is_shengxiao,ap.is_fankui,ap.tag,ap.is_hexiao,yuan.tag as yuantag,min(apd.fankui_id) as weifan,ap.isqxyd")
    	->select();
    	//echo Db::table("ap_apply")->getLastSql();
        for($i=0;$i<count($applys);$i++){
            if($applys[$i]["is_actived"]==0){
                $applys[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$applys[$i]["id"],"ywlx"=>12])->value("id");
            }else{
                if($applys[$i]["yuan_id"])
                    $applys[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$applys[$i]["id"],"ywlx"=>13])->value("id");
                else
                    $applys[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$applys[$i]["id"],"ywlx"=>11])->value("id");
            }
            //$applys[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$applys[$i]["id"],"ywlx"=>11])->value("id");
        }
    	$this->assign("applys",$applys);
    	 $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);
    	$this->assign("data",$data);
		return $this->fetch();
	}
	//获得描述
	public function getdes($did){
		$tmp=$apply_de=Db::table("ap_apply_detail")->where("id=$did")->find();
		if($tmp){
			return json_encode(["msg"=>$tmp["description"],"state"=>1]);
		}else{
			return json_encode(["msg"=>"","state"=>2]);
		}
	}
     public function baocunchuli(){
        $request = Request::instance();

        
        $data=$request->post();
        if($data){
            //print_r($data);exit;
            if($data["aid"])
                $dataup["id"]=$data["aid"];
            else
                return json_encode(["msg"=>"请正确提交","state"=>2]);
            
            if($data["title"])
                $dataup["title"]=$data["title"];
            else
                return json_encode(["msg"=>"主题不能为空","state"=>2]);
            $dataup["annex_id"]=$data["attach"];
            
            $dataup["state"]=3;
            $dataup["modifiled_on"]=date("Y-m-d H:i:s");
            $fid=11;$aid=$data["aid"];

                if($dataup["state"]==3){
                   
                    $ysres=$this->apys($data["aid"]);
                    if($ysres===0){
                        return json_encode(["msg"=>"AP预算格式尚未设定，暂不能发布申请","state"=>2]);
                    }else if($ysres==1){
                        return json_encode(["msg"=>"存在未设定预算的明细","state"=>2]);
                    }else if($ysres==2){
                        return json_encode(["msg"=>"系统设定不允许红灯超预算申请","state"=>2]);
                    }else if($ysres==3){
                        return json_encode(["msg"=>"系统设定不允许黄灯及红灯超预算申请","state"=>2]);
                    }else{
                         Db::startTrans();
                        try{
                            $res1=Db::table("ap_apply")->update($dataup);
                            $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=2")->field("yd.id")->select();
                            if($ydid){
                                $ydids=[];
                                for($i=0;$i<count($ydid);$i++){
                                    $ydids[]=$ydid[$i]["id"];
                                }
                                $yd=implode(',',$ydids);
                                
                                Db::table("yusuan_detail")->query("delete from yusuan_detail where id in ($yd)");
                            }
                            if($ysres){
                                $res2=Db::table("yusuan_detail")->insertAll($ysres);
                            }else{
                                $res2=1;
                            }
                        }catch(\Exception $e){
                            //echo $e->getMessage();
                            Db::rollBack();
                           return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
                        }
                        if($res1&&$res2){
                           $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
                            if($res["operateStatus"]=="success"){
                                Db::commit();
                                return json_encode(["msg"=>"","state"=>1]);
                            }else{
                                Db::rollBack();
                                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                            }
                        }else{
                            Db::rollBack();
                           return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                        }
                    }
                }
           
        }else{
            return json_encode(["msg"=>"请正确提交","state"=>2]);
        }
    }
     public function qxbaocunchuli(){
        $request = Request::instance();$data = $request->post();
        $fid=12;$aid=$data["aid"];
        //print_r($data);exit;
        if($data){
            $yuanid=Db::table("ap_apply")->where(["id"=>$aid])->value("yuan_id");
            $all=Db::table("ap_apply_detail")->where(["apply_id"=>$yuanid,"is_deleted"=>0])->select();
            $jishu=0;$qx=[];$did=[];
            for($i=0;$i<count($data["did"]);$i++){
                if(trim($data["quxiaoyuanyin"][$i])){
                    $qx[]=["id"=>$data["did"][$i],"yuanyin"=>$data["quxiaoyuanyin"][$i]];
                    $jishu++;
                    $did[]=$data["did"][$i];
                }
            }
            if(!$jishu){
                return json_encode(["msg"=>"至少删除一条明细","state"=>2]);
            }
            Db::startTrans();
            try{
                $removedata=[];
                for($i=0;$i<count($all);$i++){
                    for($j=0;$j<count($qx);$j++){
                        //echo $all[$i]["id"]."---".$qx[$j]["id"]."|";
                        if($all[$i]["id"]==$qx[$j]["id"]){
                            $tmp=$all[$i];
                            $tmp["yuanmingxi"]=$tmp["id"];
                            $tmp["biandongyuanyin"]=$qx[$j]["yuanyin"];
                    
                            $tmp["modifiled_on"]=date("Y-m-d H:i:s");
                            $tmp["apply_id"]=$aid;
                            $tmp["tag"]=2;
                             unset($tmp["id"]);
                             $removedata[]=$tmp;
                             //echo 1;
                        }
                    }
                }
                Db::table("ap_apply_detail")->where(["apply_id"=>$aid])->delete();
                //插入新明细
                $res2=Db::table("ap_apply_detail")->insertAll($removedata);
                //原明细取消
                $str=implode(',',$did);
                //$res3=1;
                Db::table("ap_apply_detail")->where("id in($str)")->update(["is_actived"=>0]);
                
                Db::table("ap_apply")->where(["id"=>$aid])->update(["isqxyd"=>1]);
            }catch(\Exception $e){
                //echo $e->getMessage();
                Db::rollBack();
               return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            if($res2){
                $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
                if($res["operateStatus"]=="success"){
                    Db::commit();
                    Db::table("ap_apply")->where(["id"=>$aid])->update(["state"=>3,"annex_id"=>$data["attach"]]);
                    return json_encode(["msg"=>"","state"=>1]);
                }else{
                    Db::rollBack();
                    return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
            }else{
                Db::rollBack();
               return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
        }else{
            return json_encode(["msg"=>"请正确提交","state"=>2]);
        }
    }
    public function qxzuofeichuli(){
        $request = Request::instance();$data = $request->post();
        $fid=12;$aid=$data["aid"];
        $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
        if($res["operateStatus"]=="success"){
            $yuanid=Db::table("ap_apply")->where("id=$aid")->value("yuan_id");
            try{
                Db::table("ap_apply")->where(["id"=>$yuanid])->update(["isqxyd"=>0]);
                Db::table("ap_apply")->where(["id"=>$aid])->update(["state"=>8]);
            }catch (\Exception $e){
        
                          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                        }
        return json_encode(["msg"=>"","state"=>1]);
            
        }else{
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
    }
    public function zuofeichuli(){
        $request = Request::instance();$data = $request->post();
        //print_r($data);exit;
        $fid=11;$aid=$data["aid"];$feireason=$data["feireason"];
        if(!trim($feireason))
            return json_encode(["msg"=>"作废原因不能为空","state"=>2]);
        else{
            $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
            if($res["operateStatus"]=="success"){
                $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=2")->field("yd.id")->select();
                if($ydid){
                    $ydids=[];
                    for($i=0;$i<count($ydid);$i++){
                        $ydids[]=$ydid[$i]["id"];
                    }
                    $yd=implode(',',$ydids);
                    Db::table("yusuan_detail")->query("update yusuan_detail set type=0 where id in ($yd)");
                }
                    try{
                        
                            $up["zuofeiman"]=Session::get("employee_id");
                            $up["zuofeitime"]=time();
                            $up["zuofeireason"]=$feireason;
                            $up["id"]=$aid;
                            $up["state"]=8;
                        Db::table("ap_apply")->update($up);
                    }catch (\Exception $e){
        
                          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                        }
                      return json_encode(["msg"=>"","state"=>1]);
                  
                     
        }else{
        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
      }
      
    }
    }
	//添加
	public function addform($aid=0,$from=1){
        $this->assign("from",$from);
			//获取渠道类型
		$channel=Db::table("cg_channel_types1")->select();
		$this->assign("channel",$channel);
		$this->assign("aid",$aid);
		$fujian=[];
		if($aid){
			$apply=Db::table("ap_apply")->where("id=$aid")->find();
			$this->assign("apply",$apply);
             if($apply["state"]==2){
                    $btn=$this->getbton(11,$aid);
                    $this->assign("btn",$btn);
                    $logs=$this->getlog(11,$aid);
                    //print_r($logs);
                    $this->assign("logs",$logs);
                }
			if($apply["annex_id"])
    			$fujian=Db::table("annex")->where("id in({$apply["annex_id"]})")->select();

    		$apply_de=Db::table("ap_apply_detail")->alias("apd")
    		->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    		->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    		->join("cg_market_city c","apd.shi=c.id","LEFT")
    		->join("cg_jxs j","apd.jxs=j.id","LEFT")
    		->join("cg_system s","apd.system=s.id","LEFT")
    		->join("cg_net n","apd.net=n.id","LEFT")
    		->join("pro_brands pb","apd.brand=pb.id","LEFT")
    		->join("pro_category pc","apd.category=pc.id","LEFT")
    		->join("pro_series ps","apd.series=ps.id","LEFT")
    		->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    		->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    		->join("gys g","apd.gys=g.id")
    		->join("cg_paymethod cp","apd.zfid=cp.id")
    		->where("apd.is_actived=1 and apd.is_deleted=0 and apd.apply_id=$aid")
    		->order("apd.fenqu,apd.sheng,apd.shi,apd.jxs,apd.system,apd.net,apd.brand,apd.category,apd.series,apd.id")
    		->field("apd.id,apd.detail_no,apd.is_bu,g.no as gys_no,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.start_time,apd.end_time,k2.title as kemu2,apd.zonge,apd.shuilv,apd.dikou,(apd.zonge+apd.zonge*apd.shuilv/100) as hanshui,cp.title as zffs,apd.zong_xiaoliang,apd.jizhun_xiaoliang,(apd.zong_xiaoliang-apd.jizhun_xiaoliang) as xinxiaoliang,apd.description,apd.remark,apd.yujifeiyonglv,apd.yujiroi")
    		->select();

    		$this->assign("apply_de",$apply_de);
    		$tmp=Db::table("ap_apply_detail")->query("select sum(zonge) as zonges,sum(zonge+zonge*shuilv/100) as hanshuis,sum(zong_xiaoliang) as zong_xiaoliangs,sum(zong_xiaoliang-jizhun_xiaoliang) as news from ap_apply_detail where apply_id=$aid and is_deleted=0 and is_actived=1");
    		$all=$tmp[0];
            $all["yujifeiyonglvs"]=$all["hanshuis"]/$all["zong_xiaoliangs"]*100;
            $all["yujirois"]=0;
            for($i=0;$i<count($apply_de);$i++){
                $all["yujirois"]+=($apply_de[$i]["yujiroi"]*$apply_de[$i]["hanshui"]);
            }
            $all["yujirois"]=$all["yujirois"]/$all["hanshuis"];
            // $up["yujifeiyonglv"]=($up["zonge"]+$up["zonge"]*$shuilv/100)/$up["zong_xiaoliang"]*100;
            //$up["yujiroi"]=($up["zong_xiaoliang"]-$up["jizhun_xiaoliang"])/($up["zonge"]+$up["zonge"]*$shuilv/100)/$profit*100;
		}else{
			$all=["zonges"=>"0","hanshuis"=>"0","zong_xiaoliangs"=>0,"news"=>0,"yujifeiyonglvs"=>0,"yujirois"=>0];
		}
		
		$this->assign("all",$all);
		$this->assign("fujian",$fujian);
       
		return $this->fetch();
	}
    //修改处理
    public function xiugaichuli(){
        $request = Request::instance();$data = $request->post();
       // print_r($data);exit;
        if($data){
            $apkuanian=db("system_param")->where("k='isKuaCaiNianAP'")->value('v');
            //1否0是
            if($apkuanian){
                $st=strtotime($data["start_time"]);
                $ed=strtotime($data["end_time"]);
                $cst=db("cg_cainian")->where("starttime<=$st and endtime>=$st")->value("id");
                $ced=db("cg_cainian")->where("starttime<=$ed and endtime>=$ed")->value("id");
                if($cst!=$ced){
                    return json_encode(["msg"=>"系统设定活动期间不能跨财年","state"=>2]);
                }
            }
            if($data["detail"])
                $up["id"]=$data["detail"];
            else
                return json_encode(["msg"=>"请正确提交","state"=>2]);
            if($data["gys"])
                $up["gys"]=$data["gys"];
            else
                return json_encode(["msg"=>"供应商必须选择","state"=>2]);
            if($data["feiyong_id"])
                $up["feiyong_id"]=$data["feiyong_id"];
            else
                return json_encode(["msg"=>"三级费用科目必须选择","state"=>2]);
            if($data["start_time"])
                $up["start_time"]=$data["start_time"];
            else
                return json_encode(["msg"=>"开始时间不能为空","state"=>2]);
            if($data["end_time"])
                $up["end_time"]=$data["end_time"];
            else
                return json_encode(["msg"=>"结束时间不能为空","state"=>2]);
            $up["is_bu"]=0;
            if(strtotime($up["start_time"])<strtotime(date("Y-m-d")))
                $up["is_bu"]=1;
            if($data["hexiao_time"])
                $up["hexiao_time"]=$data["hexiao_time"];
            else
                return json_encode(["msg"=>"核销时间不能为空","state"=>2]);
            if($data["zong_xiaoliang"])
                $up["zong_xiaoliang"]=$data["zong_xiaoliang"];
            else
                return json_encode(["msg"=>"总销量不能为空","state"=>2]);
            if($data["jizhun_xiaoliang"])
                $up["jizhun_xiaoliang"]=$data["jizhun_xiaoliang"];
            else
                return json_encode(["msg"=>"总销量不能为空","state"=>2]);
            if($data["zonge"])
                $up["zonge"]=$data["zonge"];
            else
                return json_encode(["msg"=>"未税总额不能为空","state"=>2]);
            if(trim($data["description"]))
                $up["description"]=trim($data["description"]);
            else
                return json_encode(["msg"=>"活动描述不能为空","state"=>2]);
            if(trim($data["remark"]))
                $up["remark"]=trim($data["remark"]);
            else
                $up["remark"]=null;
            $up["zfid"]=$data["zfid"];
            //产品
            if(isset($data["brand"])){
                if($data["brand"]){
                    $up["brand"]=$data["brand"];$up["category"]=null;$up["series"]=null;
                    $profit=Db::table("pro_brands")->where(["id"=>$up["brand"]])->value("profit");
                }else{
                    return json_encode(["msg"=>"产品品牌必须选择","state"=>2]);
                }
            }else if(isset($data["category"])){
                if($data["category"]){
                    $tmp=Db::table("pro_category")->alias("c")->join("pro_brands b","c.brand_id=b.id")->where(["c.id"=>$data["category"]])->field("b.id,b.profit")->find();
                    $up["brand"]=$tmp["id"];$up["category"]=$data["category"];$up["series"]=null;$profit=$tmp["profit"];
                }else{
                    return json_encode(["msg"=>"产品品类必须选择","state"=>2]);
                }
            }else if(isset($data["series"])){
                if($data["series"]){
                    $tmp=Db::table("pro_series")->alias("s")->join("pro_category c","s.category_id=c.id")->join("pro_brands b","c.brand_id=b.id")->where(["s.id"=>$data["series"]])->field("b.id,b.profit,c.id as cid")->find();
                    $up["brand"]=$tmp["id"];$up["category"]=$tmp["cid"];$up["series"]=$data["series"];$profit=$tmp["profit"];
                }else{
                    return json_encode(["msg"=>"产品系列必须选择","state"=>2]);
                }
            }else{
                return json_encode(["msg"=>"请正确提交","state"=>2]);
            }
            if(isset($data["fenqu"])){
                if($data["fenqu"]){
                    $up["fenqu"]=$data["fenqu"];$up["sheng"]=null;$up["shi"]=null;$up["jxs"]=null;$up["system"]=null;$up["net"]=null;
                }else{
                    return json_encode(["msg"=>"大区必须选择","state"=>2]);
                }
            }else if(isset($data["sheng"])){
                if($data["sheng"]){
                    $tmp=Db::table("cg_market_provice")->where(["id"=>$data["sheng"]])->field("zoning")->find();
                    $up["fenqu"]=$tmp["zoning"];$up["sheng"]=$data["sheng"];$up["shi"]=null;$up["jxs"]=null;$up["system"]=null;$up["net"]=null;
                }else{
                    return json_encode(["msg"=>"省份必须选择","state"=>2]);
                }

            }else if(isset($data["shi"])){
                if($data["shi"]){
                    $tmp=Db::table("cg_market_city")->alias("c")->join("cg_market_provice p","c.provice=p.id")->where(["c.id"=>$data["shi"]])->field("p.zoning,p.id as sheng")->find();
                    $up["fenqu"]=$tmp["zoning"];$up["sheng"]=$tmp["sheng"];$up["shi"]=$data["shi"];$up["jxs"]=null;$up["system"]=null;$up["net"]=null;
                }else{
                    return json_encode(["msg"=>"城市必须选择","state"=>2]);
                }
            }else if(isset($data["jxs"])){
                if($data["jxs"]){
                    $tmp=Db::table("cg_jxs")->where(["id"=>$data["jxs"]])->find();
                    $up["fenqu"]=$tmp["zoning"];$up["sheng"]=$tmp["provice"];$up["shi"]=$tmp["city"];$up["jxs"]=$data["jxs"];$up["system"]=null;$up["net"]=null;
                }else{
                    return json_encode(["msg"=>"经销商必须选择","state"=>2]);
                }
                
                
            }else if(isset($data["system"])){
                if($data["system"]){
                    $up["jxs"]=Db::table("cg_system")->where(["id"=>$data["system"]])->value("jxs");
                    $tmp=Db::table("cg_jxs")->where(["id"=>$up["jxs"]])->find();
                    $up["fenqu"]=$tmp["zoning"];$up["sheng"]=$tmp["provice"];$up["shi"]=$tmp["city"];$up["system"]=$data["system"];$up["net"]=null;
                }else{
                    return json_encode(["msg"=>"系统必须选择","state"=>2]);
                }
               
            }else if(isset($data["net"])){
                if($data["net"]){
                    $up["system"]=Db::table("cg_net")->where(["id"=>$data["net"]])->value("system_id");
                    $up["jxs"]=Db::table("cg_system")->where(["id"=>$up["system"]])->value("jxs");
                    $tmp=Db::table("cg_jxs")->where(["id"=>$up["jxs"]])->find();
                    $up["fenqu"]=$tmp["zoning"];$up["sheng"]=$tmp["provice"];$up["shi"]=$tmp["city"];$up["net"]=$data["net"];
                }else{
                    return json_encode(["msg"=>"网点必须选择","state"=>2]);
                }
            }else{
                return json_encode(["msg"=>"请正确提交","state"=>2]);
            }
            $shuilv=Db::table("ap_apply_detail")->where(["id"=>$up["id"]])->value("shuilv");
            $up["yujifeiyonglv"]=($up["zonge"]+$up["zonge"]*$shuilv/100)/$up["zong_xiaoliang"]*100;
            $up["yujiroi"]=($up["zong_xiaoliang"]-$up["jizhun_xiaoliang"])/($up["zonge"]+$up["zonge"]*$shuilv/100)/$profit*100;
            //print_r($up);exit;
            try{
                Db::table("ap_apply_detail")->update($up);
            }catch (\Exception $e){
                 
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            return json_encode(["msg"=>"","state"=>1]);
        }else{
            return json_encode(["msg"=>"请正确提交","state"=>2]);
        }
    }
	//修改
	public function xiugai($did){
        $this->assign("did",$did);
        $detail=Db::table("ap_apply_detail")->where("id=$did")->find();
        $detail["gys_name"]=Db::table("gys")->where(["id"=>$detail["gys"]])->value("gys_name");
        $detail["kemu"]=Db::table("cg_feiyongkemu3")->where(["id"=>$detail["feiyong_id"]])->value("title");
        $detail["brand_name"]=Db::table("pro_brands")->where(["id"=>$detail["brand"]])->value("brand_name");
        $detail["cate_name"]=Db::table("pro_category")->where(["id"=>$detail["category"]])->value("category_name");
        $detail["series_name"]=Db::table("pro_series")->where(["id"=>$detail["series"]])->value("series_name");
        $detail["fenqu_name"]=Db::table("cg_market_zoning")->where(["id"=>$detail["fenqu"]])->value("title");
        $detail["sheng_name"]=Db::table("cg_market_provice")->where(["id"=>$detail["sheng"]])->value("title");
        $detail["shi_name"]=Db::table("cg_market_city")->where(["id"=>$detail["shi"]])->value("title");
        $detail["jxs_name"]=Db::table("cg_jxs")->where(["id"=>$detail["jxs"]])->value("title");
        $detail["system_name"]=Db::table("cg_system")->where(["id"=>$detail["system"]])->value("title");
        $detail["net_name"]=Db::table("cg_net")->where(["id"=>$detail["net"]])->value("title");
        $this->assign("detail",$detail);
        $channel=Db::table("ap_apply")->where(["id"=>$detail["apply_id"]])->value("channel_id");
        $this->assign("channel",$channel);
        $pay=Db::table("cg_paymethod")->select();
        $this->assign("pay",$pay);
        $protype=0;
        if($detail["brand"])
            $protype++;
        if($detail["category"])
            $protype++;
        if($detail["series"])
            $protype++;
        $this->assign("protype",$protype);
        $areatype=0;
        if($detail["fenqu"])
            $areatype++;
        if($detail["sheng"])
            $areatype++;
        if($detail["shi"])
            $areatype++;
        if($detail["jxs"])
            $areatype++;
        if($detail["system"])
            $areatype++;
        if($detail["net"])
            $areatype++;
        $this->assign("areatype",$areatype);
		return $this->fetch();
	}
	 //删除明细
    public function shanchu(){
    	$request = Request::instance();

    	
    	$data=$request->post();
    	$did=$data["did"];
    	$aid=$data["aid"];
    	if(!$aid){
    		return 2;
    	}
$ck=Db::table("ap_apply_detail")->where(["apply_id"=>$aid,"is_deleted"=>0])->count();
    		Db::startTrans();
    		
        try{
        		
        		
	        	$res1=Db::table("ap_apply_detail")->where("id in($did) and apply_id=$aid")->delete();
	        	
	        	
	        }catch(\Exception $e){
	        	//echo $e->getMessage();
	        	Db::rollBack();
	           return 2;
	        }
	         if($res1&&$res1!=$ck){
				Db::commit();
	            return 1;
	        }else{
	        	Db::rollBack();
	           return 2;
	        }
    }
	//添加明细
	public function addData($area,$pro,$channel,$aid=0){


		$this->assign("area",$area);
		$this->assign("channel",$channel);
		$this->assign("pro",$pro);
		$this->assign("aid",$aid);
		return $this->fetch();
	}
	//添加单据
	public function addapply(){
			$request = Request::instance();
    	$data=$request->post();
	    if($data){
	    	//print_r($data);exit;
	    	if(trim($data["title"])){
	    		$applydata["title"]=trim($data["title"]);
	    	}else{
	    		return json_encode(["wrong"=>"主题不能为空","aid"=>0]);
	    	}
	    	if(trim($data["channel"])){
	    		$applydata["channel_id"]=$data["channel"];
	    	}else{
	    		return json_encode(["wrong"=>"渠道不能为空","aid"=>0]);
	    	}
	    	//生成单号
	    	$timenow=date("Ymd");
	        $num=Db::table("ap_apply")->where("no like '$timenow%'")->count();
	      	$num++;
	      	$strnum=$timenow.sprintf("%05d", $num);
	      	$applydata["no"]=$strnum;
	      	$applydata["c_users_id"]=Session::get("login_id");
	    	$applydata["created_on"]=date("Y-m-d H:i:s");
	    	$applydata["state"]=1;
	    	if($data["attach"]){
	    		$applydata["annex_id"]=$data["attach"];
	    	}
	    	Db::startTrans();
	        try{
	        	$res1=Db::table("ap_apply")->insertGetId($applydata);
	 			
	        	
	        	//$res2=1;
	        }catch(\Exception $e){
	        	Db::rollBack();
	            return json_encode(["wrong"=>"系统繁忙请稍后再试","aid"=>""]);
	        }
	        if($res1){
				Db::commit();
	            return json_encode(["wrong"=>"","aid"=>$res1]);
	        }else{
	        	Db::rollBack();
	            return json_encode(["wrong"=>"系统繁忙请稍后再试","aid"=>""]);
	        }

	    	
    	}else{
    		return json_encode(["wrong"=>"请正确提交","aid"=>""]);
    	}
	}
	//添加并拆分明细
	public function addapplydetail(){
			$request = Request::instance();
    	$data=$request->post();
	    if($data){
            $apkuanian=db("system_param")->where("k='isKuaCaiNianAP'")->value('v');
            //1否0是
            if($apkuanian){
                $st=strtotime($data["start"]);
                $ed=strtotime($data["end"]);
                $cst=db("cg_cainian")->where("starttime<=$st and endtime>=$st")->value("id");
                $ced=db("cg_cainian")->where("starttime<=$ed and endtime>=$ed")->value("id");
                if($cst!=$ced){
                    return json_encode(["msg"=>"系统设定活动期间不能跨财年","state"=>2]);
                }
            }
	    	//print_r($data);exit;
	    	//区域纬度处理
	    	$aid=$data["aid"];
	    	$where="apd.apply_id={$aid} and apd.is_deleted=0 ";
	    	$area=[];

	    	if(isset($data["fenqu"])){
	    		//传递分区
	    		if(trim($data["fenqu"])){
	    			
	    			$tmp=explode(',',$data["fenqu"]);

	    			for($i=0;$i<count($tmp);$i++){
	    				$area[]=["fenqu"=>$tmp[$i],"sheng"=>null,"shi"=>null,"jxs"=>null,"system"=>null,"net"=>null];
	    			}

	    			$where.="and apd.fenqu in ({$data["fenqu"]}) and apd.sheng is null and apd.shi is null and apd.jxs is null and apd.system is null and apd.net is null ";

	    		}else{
	    			return json_encode(["msg"=>"至少选择一个分区","state"=>2]);
	    		}
	    	}else if(isset($data["sheng"])){
	    		//传递省
	    		if(trim($data["sheng"])){
	    			$area=Db::table("cg_market_provice")->where("id in ({$data["sheng"]})")->field("id as sheng,zoning as fenqu")->select();
	    			for($i=0;$i<count($area);$i++){
	    				$area[$i]["shi"]=null;$area[$i]["jxs"]=null;$area[$i]["system"]=null;$area[$i]["net"]=null;
	    			}
	    			$where.="and apd.sheng in ({$data["sheng"]}) and apd.shi is null and apd.jxs is null and apd.system is null and apd.net is null ";
	    		}else{
	    			return json_encode(["msg"=>"至少选择一个省","state"=>2]);
	    		}
	    	}else if(isset($data["shi"])){
	    		//传递市
	    		if(trim($data["shi"])){
	    			$area=Db::table("cg_market_city")->alias("c")->join("cg_market_provice p","c.provice=p.id")->where("c.id in ({$data["shi"]})")->field("c.id as shi,p.id as sheng,p.zoning as fenqu")->select();
	    			for($i=0;$i<count($area);$i++){
	    				$area[$i]["jxs"]=null;$area[$i]["system"]=null;$area[$i]["net"]=null;
	    			}
	    			$where.="and apd.shi in ({$data["shi"]}) and apd.jxs is null and apd.system is null and apd.net is null ";
	    		}else{
	    			return json_encode(["msg"=>"至少选择一个市","state"=>2]);
	    		}
	    	}else if(isset($data["jxs"])){
	    		//传递经销商
	    		if(trim($data["jxs"])){
	    			$area=Db::table("cg_jxs")->where("id in ({$data["jxs"]})")->field("id as jxs,zoning as fenqu,provice as sheng,city as shi")->select();
	    			for($i=0;$i<count($area);$i++){
	    				$area[$i]["system"]=null;$area[$i]["net"]=null;
	    			}
	    			$where.="and apd.jxs in ({$data["jxs"]}) and apd.system is null and apd.net is null ";
	    		}else{
	    			return json_encode(["msg"=>"至少选择一个经销商","state"=>2]);
	    		}
	    	}else if(isset($data["system"])){
	    		//传递系统
	    		if(trim($data["system"])){
	    			$area=Db::table("cg_system")->where("id in ({$data["system"]})")->field("id as system,zoning as fenqu,provice as sheng,city as shi,jxs")->select();
	    			for($i=0;$i<count($area);$i++){
	    				$area[$i]["net"]=null;
	    			}
	    			$where.="and apd.system in ({$data["system"]}) and apd.net is null ";
	    		}else{
	    			return json_encode(["msg"=>"至少选择一个系统","state"=>2]);
	    		}
	    	}else if(isset($data["net"])){
	    		//传递网点
	    		if(trim($data["net"])){
	    			$area=Db::table("cg_net")->alias("n")->join("cg_system s","n.system_id=s.id")->where("n.id in ({$data["net"]})")->field("n.id as net,n.system_id as system,s.zoning as fenqu,s.provice as sheng,s.city as shi,s.jxs")->select();
	    			$where.="and apd.net in ({$data["net"]}) ";
	    		}else{
	    			return json_encode(["msg"=>"至少选择一个网点","state"=>2]);
	    		}
	    	}else{
	    		return json_encode(["msg"=>"请正确提交","state"=>2]);
	    	}

	    	//print_r($area);exit;
	    	//产品纬度处理
	    	$pro=[];
	    	if(isset($data["brand"])){
	    		//品牌
	    		if(trim($data["brand"])){
	    			$tmp=explode(',',$data["brand"]);
	    			for($i=0;$i<count($tmp);$i++){
	    				$pro[]=["brand"=>$tmp[$i],"category"=>null,"series"=>null];
	    			}
	    			$where.="and apd.brand in ({$data["brand"]}) and apd.category is null and apd.series is null ";
	    		}else{
	    			return json_encode(["msg"=>"至少选择一个品牌","state"=>2]);
	    		}
	    	}else if(isset($data["category"])){
	    		//品类
	    		if(trim($data["category"])){
	    			$pro=Db::table("pro_category")->where("id in ({$data["category"]})")->field("id as category,brand_id as brand")->select();
	    			for($i=0;$i<count($pro);$i++){
	    				$pro[$i]["series"]=null;
	    			}
	    			$where.="and apd.category in ({$data["category"]})  and apd.series is null ";
	    		}else{
	    			return json_encode(["msg"=>"至少选择一个类","state"=>2]);
	    		}
	    	}else if(isset($data["series"])){
	    		//系列
	    		if(trim($data["series"])){
	    			$pro=Db::table("pro_series")->alias("s")->join("pro_category c","s.category_id=c.id")->where("s.id in ({$data["series"]})")->field("s.id as series,c.id as category,c.brand_id as brand")->select();
	    			
	    			$where.="and apd.series in ({$data["series"]}) ";
	    		}else{
	    			return json_encode(["msg"=>"至少选择一个系列","state"=>2]);
	    		}
	    	}else{
	    		return json_encode(["msg"=>"请正确提交","state"=>2]);
	    	}
	    	//return json_encode(["msg"=>"aaa","state"=>"2"]);
	    	//验证基本信息
	    	if(!$data["yjverifyTime"])
    			return json_encode(["msg"=>"预计核销时间不能为空","state"=>"2"]);
    		if(!$data["start"])
    			return json_encode(["msg"=>"活动开始时间不能为空","state"=>"2"]);
    		if(!$data["end"])
    			return json_encode(["msg"=>"活动结束时间不能为空","state"=>"2"]);
    		if(!$data["yjallshop"])
    			return json_encode(["msg"=>"预计总销量不能为空且必须大于0","state"=>"2"]);
    		if(!$data["allbaseshop"])
    			return json_encode(["msg"=>"总基准销量不能为空且必须大于0","state"=>"2"]);
    		if(!$data["description"])
    			return json_encode(["msg"=>"项目描述不能为空","state"=>"2"]);
    		$is_bu=0;
    		$nowday=strtotime(date("Y-m-d"));
    		$starttime=strtotime($data["start"]);
    		if($starttime<$nowday)
    			$is_bu=1;

    		//循环验证费用科目明细
    		//print_r($data);exit;
    		$strfeiyong=implode(',',$data["feiyong"]);
    		$where.="and apd.feiyong_id in ({$strfeiyong})";
    		$feiyong=[];
    		for($i=0;$i<count($data["feiyong"]);$i++){
    			if(!$data["feiyong"][$i])
    				return json_encode(["msg"=>"费用科目必须选择","state"=>2]);
    			if(!$data["gys"][$i])
    				return json_encode(["msg"=>"供应商必须选择","state"=>2]);
    			if(!$data["weishui"][$i])
    				return json_encode(["msg"=>"未税金额必须填写且不能为0","state"=>2]);
    			if(!$data["zfid"][$i])
    				return json_encode(["msg"=>"支付方式必须选择","state"=>2]);
    			$feiyong[]=["feiyong_id"=>$data["feiyong"][$i],"gys"=>$data["gys"][$i],"zonge"=>$data["weishui"][$i],"dikou"=>$data["isdi"][$i],"shuilv"=>$data["shuilv"][$i],"zfid"=>$data["zfid"][$i]];
    		}

    		//验证重复
    		//echo $where;
    		$ishas=Db::table("ap_apply_detail")->alias("apd")
    		->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    		->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    		->join("cg_market_city c","apd.shi=c.id","LEFT")
    		->join("cg_jxs j","apd.jxs=j.id","LEFT")
    		->join("cg_system s","apd.system=s.id","LEFT")
    		->join("cg_net n","apd.net=n.id","LEFT")
    		->join("pro_brands pb","apd.brand=pb.id","LEFT")
    		->join("pro_category pc","apd.category=pc.id","LEFT")
    		->join("pro_series ps","apd.series=ps.id","LEFT")
    		->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    		->where($where)
    		->field("z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu")
    		->find();
    		if($ishas){
    			$str="分区:{$ishas["fenqu"]} ";
    			if($ishas["sheng"])
    				$str.="省份:{$ishas["sheng"]} ";
    			if($ishas["shi"])
    				$str.="城市:{$ishas["shi"]} ";
    			if($ishas["jxs"])
    				$str.="经销商:{$ishas["jxs"]} ";
    			if($ishas["system"])
    				$str.="系统:{$ishas["system"]} ";
    			if($ishas["net"])
    				$str.="网点:{$ishas["net"]} ";
    			$str.="中已存在对于产品 品牌:{$ishas["brand"]}";
    			if($ishas["category"])
    				$str.="品类:{$ishas["category"]} ";
    			if($ishas["series"])
    				$str.="系列:{$ishas["series"]} ";
    			$str.="对于费用科目{$ishas["kemu"]}的设置不能重复添加";
    			return json_encode(["msg"=>$str,"state"=>2]);
    		}
    		//验证通过组合数据
    		$areanum=count($area);
    		$pronum=count($pro);
    		$feiyonnum=count($feiyong);
    	
    		$nownum=Db::table("ap_apply_detail")->where("apply_id=$aid")->max("detail_no");
    		$nownum++;
    		$adddatas=[];
    			//
    		for($i=0;$i<$areanum;$i++){
    			//i区域
    			for($j=0;$j<$pronum;$j++){
    				//产品
                    $profit=Db::table("pro_brands")->where(["id"=>$pro[$j]["brand"]])->value("profit");
    				for($k=0;$k<$feiyonnum;$k++){
    					//费用
    					
    					$adddata["detail_no"]=$nownum;$adddata["apply_id"]=$aid;
    					$adddata["fenqu"]=$area[$i]["fenqu"];$adddata["sheng"]=$area[$i]["sheng"];$adddata["shi"]=$area[$i]["shi"];
    					$adddata["jxs"]=$area[$i]["jxs"];$adddata["system"]=$area[$i]["system"];$adddata["net"]=$area[$i]["net"];

    					$adddata["brand"]=$pro[$j]["brand"]; $adddata["category"]=$pro[$j]["category"];$adddata["series"]=$pro[$j]["series"];

    					$adddata["start_time"]=$data["start"];$adddata["end_time"]=$data["end"];$adddata["hexiao_time"]=$data["yjverifyTime"];
    					$adddata["zong_xiaoliang"]=$data["yjallshop"]/$areanum/$pronum/$feiyonnum;
    					$adddata["jizhun_xiaoliang"]=$data["allbaseshop"]/$areanum/$pronum/$feiyonnum;
    					$adddata["feiyong_id"]=$feiyong[$k]["feiyong_id"];$adddata["gys"]=$feiyong[$k]["gys"];$adddata["zonge"]=$feiyong[$k]["zonge"]/$areanum/$pronum;
                        $adddata["pifuzonge"]=$feiyong[$k]["zonge"]/$areanum/$pronum;
    					$adddata["zfid"]=$feiyong[$k]["zfid"];$adddata["dikou"]=$feiyong[$k]["dikou"];$adddata["created_on"]=date("Y-m-d H:i:s");
						$adddata["is_bu"]=$is_bu;$adddata["description"]=$data["description"];$adddata["remark"]=$data["remark"];
						$adddata["shuilv"]=$feiyong[$k]["shuilv"];
                        $adddata["yujifeiyonglv"]=($adddata["zonge"]+$adddata["zonge"]*$adddata["shuilv"]/100)/$adddata["zong_xiaoliang"]*100;
                        $adddata["yujiroi"]=($adddata["zong_xiaoliang"]-$adddata["jizhun_xiaoliang"])/($adddata["zonge"]+$adddata["zonge"]*$adddata["shuilv"]/100)/$profit*100;
    					$adddatas[]=$adddata;
    					$nownum++;
    				}
    			}
    		}//print_r($adddatas);exit;

//return json_encode(["msg"=>count($adddatas),"state"=>2]);
    		//插入明细
    		Db::startTrans();
	        try{
	        	$res1=Db::table("ap_apply_detail")->insertAll($adddatas);
	 			
	        }catch(\Exception $e){
	        	Db::rollBack();
	            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }
	        if($res1){
				Db::commit();
	            return json_encode(["msg"=>"","state"=>1]);
	        }else{
	        	Db::rollBack();
	             return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }

	    	
    	
	    }else{
	    	return json_encode(["msg"=>"请正确提交","state"=>2]);
	    }

	}
	//增加费用科目
	public function addfeiyong($id=2,$title="aaa"){
		 //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
          $str = '';
        foreach($fipay as $k=>$v){
            $str .= '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }
			 echo <<<EOF
 		  <tr class="infoContent " fid="{$id}">
            <td><input type="hidden" name="feiyong[]" value="{$id}"/>
				 <div class="selectedOnlyOne " >
                                	
                    <span class="inin">{$title}</span>
                    <span class="closeit">×</span>
                 </div>
            </td>
            <td>
				<div class="container-fluid">
                        <div class="row">
                            <div class="col-xs-8">
                                <div class="input-group" >
                                    <input type="text" placeholder="请输入关键字或空格查询" class="form-control gys" name="gys[]" value="">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="selectedOnlyOne " style="display:none;" >
                                	
                                    <span class="inin"></span>
                                    <span class="close">×</span>
                                </div>
                            </div>
                            <div class="col-xs-4">
                                <button type="button" class="btn btn-primary select_gys" >选择</button>
                            </div>
                        </div>
                    </div>
				
            </td>
            <td><input type="text" class="form-control weishui" style="min-width: 100px;width: 100px" value="0.00" name="weishui[]"></td>
            <td>
              <div class="form-group">
              	<input type="hidden" value="1" name="isdi[]"/>
                   <label class="radio-inline">
			          <input type="radio" name="is_addtax{$id}" class="isshi"  value="1" checked>是
			        </label>
                    <label class="radio-inline">
			          <input type="radio" name="is_addtax{$id}" class="isfou"  value="0">否
			        </label>

              </div>
            </td>
           
              <td><input type="text" class="form-control shuilv" style="min-width: 60px;width: 60px" value="0.00" name="shuilv[]">&nbsp;%</td>
            <td><input type="text" class="form-control hanshui" value="0.00" readonly></td>  
            <td><input type="text" class="form-control shiji" value="0.00" readonly></td>
            <td>
            <select name="zfid[]" class="form-control zfid">
                <option value="0">请选择</option>
                {$str}
            </select>
            </td>
        </tr>
EOF;
	}
   
	  //保存申请
    
    public function baocunapply(){
    	$request = Request::instance();

    	
    	$data=$request->post();
    	if($data){
    		//print_r($data);exit;
    		if($data["aid"])
    			$dataup["id"]=$data["aid"];
    		else
    			return json_encode(["msg"=>"请正确提交","state"=>2]);
    		
    		if($data["title"])
    			$dataup["title"]=$data["title"];
    		else
    			return json_encode(["msg"=>"主题不能为空","state"=>2]);
    		$dataup["annex_id"]=$data["fujian"];
    		
    		$dataup["state"]=1;
    		$dataup["modifiled_on"]=date("Y-m-d H:i:s");
    			
	        	if($data["state"]==3){
                   
                    $ysres=$this->apys($data["aid"]);
                    if($ysres===0){
                        return json_encode(["msg"=>"AP预算格式尚未设定，暂不能发布申请","state"=>2]);
                    }else if($ysres==1){
                        return json_encode(["msg"=>"存在未设定预算的明细","state"=>2]);
                    }else if($ysres==2){
                        return json_encode(["msg"=>"系统设定不允许红灯超预算申请","state"=>2]);
                    }else if($ysres==3){
                        return json_encode(["msg"=>"系统设定不允许黄灯及红灯超预算申请","state"=>2]);
                    }else{
                         Db::startTrans();
                        try{
                            $res1=Db::table("ap_apply")->update($dataup);
                            if($ysres){
                                $res2=Db::table("yusuan_detail")->insertAll($ysres);
                            }else{
                                $res2=1;
                            }
                        }catch(\Exception $e){
                            //echo $e->getMessage();
                            Db::rollBack();
                           return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
                        }
                        if($res1&&$res2){
                            $jieguo=$this->gowork(11,$data["aid"]);
                            if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                                Db::commit();
                                return $jieguo;
                            }else{
                                Db::rollBack();
                                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                            }
                        }else{
                            Db::rollBack();
                           return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                        }
                    }
                }else{
                     try{   
                            $res1=Db::table("ap_apply")->update($dataup);
                        }catch(\Exception $e){
                            //echo $e->getMessage();
                            Db::rollBack();
                           return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                        }
                         if($res1){

                            Db::commit();
                        

                            return json_encode(["msg"=>"","state"=>1]);
                        }else{
                            Db::rollBack();
                          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                        }
                }
	       
    	}else{
    		return json_encode(["msg"=>"请正确提交","state"=>2]);
    	}
    }
    //ap预算匹配
    public function apys($aid){
        $ischao=db("system_param")->where("k='isChaoYuSuan'")->value('v');
        //1红 2黄  0无
        //$jifanshi=db("system_param")->where("k='tiYuSuanShiJian'")->value('v');
        //0财年 1当前 2累计  
        
        $apply=Db::table("ap_apply")->where(["id"=>$aid])->find();
        $applyde=Db::table("ap_apply_detail")->where(["apply_id"=>$aid,"is_deleted"=>0])->select();
        $aptar=Db::table("target_format")->where(["type_id"=>3])->find();
        $isred=0;
        $isyellow=0;
        $isnohas=0;
        if($aptar){
            $yusuan=[];

            for($i=0;$i<count($applyde);$i++){
                $where="type=2 ";
                $sanjifeiyong=$applyde[$i]["feiyong_id"];
                $erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
                $yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
                $start=strtotime($applyde[$i]["start_time"]);
                $end=strtotime($applyde[$i]["end_time"]);
                $tianshu=($end-$start)/24/3600+1;
                //echo $tianshu;
                if($aptar["channel_id"]){
                    $where.="and channel1={$apply["channel_id"]} ";
                }
                if($aptar["product_id"]){
                    if($aptar["product_id"]==11){
                        $where.="and pinpai={$applyde[$i]["brand"]} and pinlei is null and xilie is null ";
                    }else if($aptar["product_id"]==12){
                        if($applyde[$i]["category"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie is null ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }else if($aptar["product_id"]==13){
                        if($applyde[$i]["series"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie={$applyde[$i]["series"]} ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }
                }else{
                    $where.="and pinpai is null and pinlei is null and xilie is null ";
                }
                if($aptar["area_id"]||$aptar["client_id"]){
                    if($aptar["area_id"]==20){
                        $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng is null and shi is null and jingxiao is null ";
                    }else if($aptar["area_id"]==21){
                        if($applyde[$i]["sheng"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi is null and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["area_id"]==22){
                        if($applyde[$i]["shi"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["client_id"]==8){
                        if($applyde[$i]["jxs"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao={$applyde[$i]["jxs"]} ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }
                }else{
                    $where.="and fenqu is null and sheng is null and shi is null and jingxiao is null ";
                }
                if($aptar["feiyong_id"]){
                    if($aptar["feiyong_id"]==16){
                        $where.="and sanjifeiyong=$sanjifeiyong ";
                    }else if($aptar["feiyong_id"]==15){
                        $where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
                    }else{
                        $where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
                    }
                }else{
                    $where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
                }
                if($aptar["kaoheqi"]==18){
                    //二级考核期
                    $kaohes=Db::table("cg_kaoheqi2")->alias("k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->where("k2.endtime>=$start and k2.starttime<=$end")->field("k2.id,k2.title,k2.pid,k1.cid,k2.starttime,k2.endtime")->select();
                    for($j=0;$j<count($kaohes);$j++){
                        $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                        $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                        $ts=($jisuanend-$jisuanstart)/24/3600+1;
                        //echo "-".$ts;
                        $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and yijikaoheqi={$kaohes[$j]["pid"]} and erjikaoheqi={$kaohes[$j]["id"]}";
                        //echo $fullwhere;exit;
                        $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                        if($yusuanpipei){
                            $hanshui=($applyde[$i]["pifuzonge"]+$applyde[$i]["pifuzonge"]*$applyde[$i]["shuilv"]/100)/$tianshu*$ts;
                            $tmpy=["yid"=>$yusuanpipei["id"],"did"=>$applyde[$i]["id"],"aid"=>$aid,"jine"=>$hanshui,"type"=>1,"tianshu"=>$ts,"zongtianshu"=>$tianshu];
                            $yusuan[]=$tmpy;
                            //验证红黄灯
                            $tmpzje=db("yusuan")->where(["id"=>$yusuanpipei["id"]])->value("jine");
                            $tmpsyje=db("yusuan_detail")->where(["yid"=>$yusuanpipei["id"],"type"=>2])->sum("jine");
                            if(!$tmpsyje)
                                $tmpsyje=0;
                            $tmpsqje=db("yusuan_detail")->where(["yid"=>$yusuanpipei["id"],"type"=>1])->sum("jine");
                            if(!$tmpsqje)
                                $tmpsqje=0;
                            if($tmpsyje>$tmpzje){
                                $isred=1;
                            }else if($tmpsyje+$tmpsqje>$tmpzje){
                                $isyellow=1;
                            }
                        }else{
                            $isnohas=1;
                        }
                    }
                }else{
                    //一级考核期
                    $kaohes=Db::table("cg_kaoheqi1")->where("endtime>=$start and starttime<=$end")->field("id,title,cid,starttime,endtime")->select();
                    for($j=0;$j<count($kaohes);$j++){
                        $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                        $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                        $ts=($jisuanend-$jisuanstart)/24/3600+1;
                        $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and yijikaoheqi={$kaohes[$j]["id"]} and erjikaoheqi is null";
                        //echo $fullwhere;exit;
                        $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                        if($yusuanpipei){
                            $hanshui=($applyde[$i]["pifuzonge"]+$applyde[$i]["pifuzonge"]*$applyde[$i]["shuilv"]/100)/$tianshu*$ts;
                            $tmpy=["yid"=>$yusuanpipei["id"],"did"=>$applyde[$i]["id"],"aid"=>$aid,"jine"=>$hanshui,"type"=>1,"tianshu"=>$ts,"zongtianshu"=>$tianshu];
                            $yusuan[]=$tmpy;
                            //验证红黄灯
                            $tmpzje=db("yusuan")->where(["id"=>$yusuanpipei["id"]])->value("jine");
                            $tmpsyje=db("yusuan_detail")->where(["yid"=>$yusuanpipei["id"],"type"=>2])->sum("jine");
                            if(!$tmpsyje)
                                $tmpsyje=0;
                            $tmpsqje=db("yusuan_detail")->where(["yid"=>$yusuanpipei["id"],"type"=>1])->sum("jine");
                            if(!$tmpsqje)
                                $tmpsqje=0;
                            if($tmpsyje>$tmpzje){
                                $isred=1;
                            }else if($tmpsyje+$tmpsqje>$tmpzje){
                                $isyellow=1;
                            }
                        }else{
                            $isnohas=1;
                        }
                    }
                }
            }
            if($ischao){
                if($isnohas){
                    return 1;
                }
                if($ischao==1&&$isred==1){
                    return 2;
                }
                if($ischao==2&&($isred==1||$isyellow==1)){
                    return 3;
                }
            }
            //print_r($yusuan);exit;
            return $yusuan;
        }else{
            return 0;//未设定格式
        }
       
    }
    //改变申请状态
     public function gostate($aid,$state){

        //找寻预算
    	$data["id"]=$aid;
        $apply=Db::table("ap_apply")->where(["id"=>$aid])->find();
    	$data["modifiled_on"]=date("Y-m-d H:i:s");

        if($apply["is_actived"]==1&&$apply["yuan_id"]==""){
            $ysres=$this->apys($aid);
           
        }else{
            $ysres=[];
        }
        
        if($ysres===0){
            return json_encode(["msg"=>"AP预算格式尚未设定，暂不能发布申请","state"=>2]);
        }else if($ysres==1){
            return json_encode(["msg"=>"存在未设定预算的明细","state"=>2]);
        }else if($ysres==2){
            return json_encode(["msg"=>"系统设定不允许红灯超预算申请","state"=>2]);
        }else if($ysres==3){
            return json_encode(["msg"=>"系统设定不允许黄灯及红灯超预算申请","state"=>2]);
        }else{
            Db::startTrans();
            try{
                $res1=Db::table("ap_apply")->update($data);
                if($ysres){
                    $res2=Db::table("yusuan_detail")->insertAll($ysres);
                }else{
                    $res2=1;
                }
            }catch(\Exception $e){
                //echo $e->getMessage();
                Db::rollBack();
               return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
            }
            if($res1&&$res2){
                if($apply["is_actived"]==1){
                    if($apply["yuan_id"])
                        $jieguo=$this->gowork(13,$aid);
                    else   
                        $jieguo=$this->gowork(11,$aid);
                }else{
                     
                    $jieguo=$this->gowork(12,$aid);
                }
                if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                    Db::commit();
                    return $jieguo;
                }else{
                    Db::rollBack();
                    return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
            }else{
                Db::rollBack();
               return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
        }
        
        		
        	
	        	
	        	
	        	
	       
    }
    public function ydzuofeichuli(){
        $request = Request::instance();$data = $request->post();
        
        //print_r($data);exit;
        $fid=13;$aid=$data["aid"];
        $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
        //$res["operateStatus"]="success";
            if($res["operateStatus"]=="success"){
                $yuanid=Db::table("ap_apply")->where(["id"=>$aid])->value("yuan_id");
                $updata["id"]=$aid;
                $updata["state"]=8;
                $updata["modifiled_on"]=date("Y-m-d H:i:s");
                Db::startTrans();
            try{
                
            
                $res1=Db::table("ap_apply")->update($updata);
                // Db::rollBack();return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                if($yuanid){
                    Db::table("ap_apply")->where(["id"=>$yuanid])->update(["isqxyd"=>0]);
                }
                
            }catch(\Exception $e){
                //echo $e->getMessage();
                Db::rollBack();
               return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
            }
             if($res1){

                Db::commit();
            

                return json_encode(["msg"=>"","state"=>1]);
            }else{
                Db::rollBack();
              return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            }else{
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
        
    }
    //删除申请
     public function shanchuap($aid){
        $yuanid=Db::table("ap_apply")->where(["id"=>$aid])->value("yuan_id");
    	$data["id"]=$aid;
    	$data["is_deleted"]=1;
    	$data["modifiled_on"]=date("Y-m-d H:i:s");
Db::startTrans();
        try{
        		
        	
	        	$res1=Db::table("ap_apply")->update($data);
	        	if($yuanid){
                    Db::table("ap_apply")->where(["id"=>$yuanid])->update(["isqxyd"=>0]);
                }
	        	
	        }catch(\Exception $e){
	        	//echo $e->getMessage();
	        	Db::rollBack();
	           return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
	        }
	         if($res1){

				Db::commit();
			

	            return json_encode(["msg"=>"","state"=>1]);
	        }else{
	        	Db::rollBack();
	          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }
    }
    //异动
    public function yidong($aid){
    	$this->assign("aid",$aid);
    	$apply=Db::table("ap_apply")->alias("ap")
    	->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
    	->join("ap_apply next","ap.next_id=next.id","LEFT")
    	->join("ti_state s","ap.state=s.id")
    	 ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
      
    	->where(["ap.id"=>$aid,"de.index"=>1])
    	->field("ap.title,ap.no,yuan.no as yuanno,next.no as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.created_on")
    	->find();
    	$this->assign("apply",$apply);
    	$applyde=Db::table("ap_apply_detail")->alias("apd")
    		->join("ap_apply ap","apd.apply_id=ap.id")
    		->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    		->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    		->join("cg_market_city c","apd.shi=c.id","LEFT")
    		->join("cg_jxs j","apd.jxs=j.id","LEFT")
    		->join("cg_system s","apd.system=s.id","LEFT")
    		->join("cg_net n","apd.net=n.id","LEFT")
    		->join("pro_brands pb","apd.brand=pb.id","LEFT")
    		->join("pro_category pc","apd.category=pc.id","LEFT")
    		->join("pro_series ps","apd.series=ps.id","LEFT")
    		->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    		->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    		->join("gys g","apd.gys=g.id")
    		->join("cg_paymethod cp","apd.zfid=cp.id")
    		->where("apd.is_actived=1 and apd.is_deleted=0 and apd.apply_id=$aid")
    		->order("apd.id")
    		->field("apd.id,apd.detail_no,apd.is_bu,g.no as gys_no,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.start_time,apd.end_time,k2.title as kemu2,apd.zonge,apd.shuilv,apd.dikou,(apd.zonge+apd.zonge*apd.shuilv/100) as hanshui,cp.title as zffs,apd.zong_xiaoliang,apd.jizhun_xiaoliang,(apd.zong_xiaoliang-apd.jizhun_xiaoliang) as xinxiaoliang,apd.description,apd.remark,apd.tag,ap.no,apd.start_time,apd.end_time,apd.hexiao_time,apd.pifuzonge,apd.zfid")
    		->select();
    	$contfenqu=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct fenqu");
    	$contbrand=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct brand");
    	$contgys=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct gys");
    		$feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid group by k3.id,k3.title");
    	$this->assign("contfenqu",$contfenqu);
    	$this->assign("contbrand",$contbrand);
    	$this->assign("contgys",$contgys);
    	$this->assign("feiyongs",$feiyongs);
    	$contfeiyong=count($feiyongs);
    	$this->assign("contfeiyong",$contfeiyong);
    	$this->assign("applyde",$applyde);

    		 //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);
    	return $this->fetch();
    }
     //异动操作
    public function yidongchuli(){
    		$request = Request::instance();

    	
    	$data=$request->post();

    	if($data){
    		//print_r($data);exit;
    		$yd=[];$yddid=[];
    		$j=0;
    		for($i=0;$i<count($data["did"]);$i++){
    			if(trim($data["yidongyuanyin"][$i])){
    				$yd[$j]["did"]=$data["did"][$i];
    				$yd[$j]["zonge"]=$data["zonge"][$i];
    				$yd[$j]["jizhun_xiaoliang"]=$data["jizhun_xiaoliang"][$i];
    				$yd[$j]["dikou"]=$data["dikou"][$i];
    				$yd[$j]["shuilv"]=$data["shuilv"][$i];
    				$yd[$j]["zfid"]=$data["zfid"][$i];
    				$yd[$j]["start_time"]=$data["start_time"][$i];
    				$yd[$j]["end_time"]=$data["end_time"][$i];
    				$yd[$j]["hexiao_time"]=$data["hexiao_time"][$i];
    				$yd[$j]["yidongyuanyin"]=$data["yidongyuanyin"][$i];
    				$yddid[$j]=$data["did"][$i];
    				$j++;
    			}
    		}
    		//print_r($yd);exit;
    		if(!$yd){
				return json_encode(["msg"=>"至少一条明细发生异动","state"=>2]);
    		}
    		$aid=$data["aid"];
    		Db::startTrans();
    		try{
    			    		//原单
	    		$apply=Db::table("ap_apply")->where(["id"=>$aid])->find();
	    		
	    		//生成单号
	    		 $timenow=date("Ymd");
	       		$num=Db::table("ap_apply")->where("no like '$timenow%'")->count();
	      		 $num++;
	      		 $strnum=$timenow.sprintf("%05d", $num);
	      		 $addapply=$apply;
	      		 unset($addapply["id"]);
	      		 $addapply["no"]=$strnum;$addapply["created_on"]=date("Y-m-d H:i:s");$addapply["modifiled_on"]=null;
				$addapply["yuan_id"]=$aid;
				$addapply["state"]=1;
				$addapply["annex_id"]=$data["attach"];
				$addapply["is_shengxiao"]=0;
				
				//print_r($addapply);exit;
				$res1=Db::table("ap_apply")->insertGetId($addapply);
				//echo $res1;exit;
				//原明细
	    		$applymx=Db::table("ap_apply_detail")->where(["apply_id"=>$aid,"is_deleted"=>0])->select();

	    		//生成新明细
	    		$datayd=[];
	    		for($i=0;$i<count($applymx);$i++){
	    			if(in_array($applymx[$i]["id"], $yddid)){
	    				//异动
	    				$tmp=$applymx[$i];
	    				for($j=0;$j<count($yd);$j++){
	    					if($yd[$j]["did"]==$tmp["id"]){

	    						//异动修改
	    						
	    						$tmp["jizhun_xiaoliang"]=$yd[$j]["jizhun_xiaoliang"];
			    				$tmp["zonge"]=$yd[$j]["zonge"];$tmp["pifuzonge"]=$yd[$j]["zonge"];
			    				$tmp["dikou"]=$yd[$j]["dikou"];$tmp["shuilv"]=$yd[$j]["shuilv"];
			    				$tmp["zfid"]=$yd[$j]["zfid"];$tmp["start_time"]=$yd[$j]["start_time"];
			    				$tmp["end_time"]=$yd[$j]["end_time"];$tmp["hexiao_time"]=$yd[$j]["hexiao_time"];
			    				$tmp["biandongyuanyin"]=$yd[$j]["yidongyuanyin"];$tmp["tag"]=1;
                                $tmp["yujifeiyonglv"]=($tmp["zonge"]+$tmp["zonge"]*$tmp["shuilv"]/100)/$tmp["zong_xiaoliang"]*100;
                                $profit=Db::table("pro_brands")->where(["id"=>$tmp["brand"]])->value("profit");
                                $tmp["yujiroi"]=($tmp["zong_xiaoliang"]-$tmp["jizhun_xiaoliang"])/($tmp["zonge"]+$tmp["zonge"]*$tmp["shuilv"]/100)/$profit*100;
                                /*
                                
                                $up["yujifeiyonglv"]=($up["zonge"]+$up["zonge"]*$shuilv/100)/$up["zong_xiaoliang"]*100;
            $up["yujiroi"]=($up["zong_xiaoliang"]-$up["jizhun_xiaoliang"])/($up["zonge"]+$up["zonge"]*$shuilv/100)/$profit*100;
                                 */
	    					}
	    				}
	    				$tmp["yuanmingxi"]=$tmp["id"];
	    				unset($tmp["id"]);
	    				$datayd[$i]=$tmp;
	    				
	    			}else{
	    				$tmp=$applymx[$i];
	    				$tmp["yuanmingxi"]=$tmp["id"];$tmp["tag"]=0;$tmp["biandongyuanyin"]=null;
	    				unset($tmp["id"]);
	    				$datayd[$i]=$tmp;
	    			}
	    			$datayd[$i]["apply_id"]=$res1;
	    		}
	    		//print_r($datayd);exit;
	    		$res2=Db::table("ap_apply_detail")->insertAll($datayd);
	    		Db::table("ap_apply")->where(["id"=>$aid])->update(["isqxyd"=>1]);
    		}catch(\Exception $e){
	        	//echo $e->getMessage();
	        	Db::rollBack();
	           return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }
	         if($res1&&$res2){
                if($data["state"]==3){
                    $jieguo=$this->gowork(13,$res1);
                    if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                        Db::commit();
                        return $jieguo;
                    }else{
                        Db::rollBack();
                        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                    }
                }else{
                    Db::commit();
                    return json_encode(["msg"=>"","state"=>1]);
                }
				
	        }else{
	        	Db::rollBack();
	          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }

    		//print_r($datayd);exit;
    	}else{
    		return json_encode(["msg"=>"请正确提交","state"=>2]);
    	}
    }
    //取消
    public function quxiao($aid){
    	$this->assign("aid",$aid);
    	$apply=Db::table("ap_apply")->alias("ap")
    	->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
    	->join("ap_apply next","ap.next_id=next.id","LEFT")
    	->join("ti_state s","ap.state=s.id")
    	 ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
      
    	->where(["ap.id"=>$aid,"de.index"=>1])
    	->field("ap.title,ap.no,yuan.no as yuanno,next.no as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.created_on")
    	->find();
    	$this->assign("apply",$apply);
    	$applyde=Db::table("ap_apply_detail")->alias("apd")
    		->join("ap_apply ap","apd.apply_id=ap.id")
    		->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    		->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    		->join("cg_market_city c","apd.shi=c.id","LEFT")
    		->join("cg_jxs j","apd.jxs=j.id","LEFT")
    		->join("cg_system s","apd.system=s.id","LEFT")
    		->join("cg_net n","apd.net=n.id","LEFT")
    		->join("pro_brands pb","apd.brand=pb.id","LEFT")
    		->join("pro_category pc","apd.category=pc.id","LEFT")
    		->join("pro_series ps","apd.series=ps.id","LEFT")
    		->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    		->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    		->join("gys g","apd.gys=g.id")
    		->join("cg_paymethod cp","apd.zfid=cp.id")
    		->where("apd.is_actived=1 and apd.is_deleted=0 and apd.apply_id=$aid")
    		->order("apd.id")
    		->field("apd.id,apd.detail_no,apd.is_bu,g.no as gys_no,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.start_time,apd.end_time,k2.title as kemu2,apd.zonge,apd.shuilv,apd.dikou,(apd.zonge+apd.zonge*apd.shuilv/100) as hanshui,cp.title as zffs,apd.zong_xiaoliang,apd.jizhun_xiaoliang,(apd.zong_xiaoliang-apd.jizhun_xiaoliang) as xinxiaoliang,apd.description,apd.remark,apd.tag,ap.no,apd.start_time,apd.end_time,apd.hexiao_time,apd.pifuzonge,apd.zfid,yujifeiyonglv,yujiroi")
    		->select();
    	$contfenqu=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct fenqu");
    	$contbrand=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct brand");
    	$contgys=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct gys");
    	$feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid group by k3.id,k3.title");
    	$this->assign("contfenqu",$contfenqu);
    	$this->assign("contbrand",$contbrand);
    	$this->assign("contgys",$contgys);
    	$this->assign("feiyongs",$feiyongs);
    	$contfeiyong=count($feiyongs);
    	$this->assign("contfeiyong",$contfeiyong);
    	$this->assign("applyde",$applyde);
     	return $this->fetch();
    }
    //取消
    public function qxzuofei($aid,$from=1){
       
        $this->assign("from",$from);
        $this->assign("aid",$aid);
        $aps=Db::table("ap_apply")->where(["id"=>$aid])->find();
        $yuanid=$aps["yuan_id"];
        $apply=Db::table("ap_apply")->alias("ap")
        ->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
        ->join("ap_apply next","ap.next_id=next.id","LEFT")
        ->join("ti_state s","ap.state=s.id")
         ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
      
        ->where(["ap.id"=>$yuanid,"de.index"=>1])
        ->field("ap.title,ap.no,yuan.no as yuanno,next.no as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.created_on")
        ->find();
        $apply["fujian"]=$aps["annex_id"];
        $fujian=[];
            //print_r($apply);
            if($apply["fujian"]){
                $fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
                //print_r($fujian);
            }
        $this->assign("fujian",$fujian);
       // print_r($fujian);
        $this->assign("apply",$apply);
        $applyde=Db::table("ap_apply_detail")->alias("apd")
            ->join("ap_apply ap","apd.apply_id=ap.id")
            ->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
            ->join("cg_market_provice p","apd.sheng=p.id","LEFT")
            ->join("cg_market_city c","apd.shi=c.id","LEFT")
            ->join("cg_jxs j","apd.jxs=j.id","LEFT")
            ->join("cg_system s","apd.system=s.id","LEFT")
            ->join("cg_net n","apd.net=n.id","LEFT")
            ->join("pro_brands pb","apd.brand=pb.id","LEFT")
            ->join("pro_category pc","apd.category=pc.id","LEFT")
            ->join("pro_series ps","apd.series=ps.id","LEFT")
            ->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
            ->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
            ->join("gys g","apd.gys=g.id")
            ->join("cg_paymethod cp","apd.zfid=cp.id")
            ->where("apd.is_actived=1 and apd.is_deleted=0 and apd.apply_id=$yuanid")
            ->order("apd.id")
            ->field("apd.id,apd.detail_no,apd.is_bu,g.no as gys_no,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.start_time,apd.end_time,k2.title as kemu2,apd.zonge,apd.shuilv,apd.dikou,(apd.zonge+apd.zonge*apd.shuilv/100) as hanshui,cp.title as zffs,apd.zong_xiaoliang,apd.jizhun_xiaoliang,(apd.zong_xiaoliang-apd.jizhun_xiaoliang) as xinxiaoliang,apd.description,apd.remark,apd.tag,ap.no,apd.start_time,apd.end_time,apd.hexiao_time,apd.pifuzonge,apd.zfid,yujifeiyonglv,yujiroi")
            ->select();
        $contfenqu=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct fenqu");
        $contbrand=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct brand");
        $contgys=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid")->count("distinct gys");
        $feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid group by k3.id,k3.title");
        $this->assign("contfenqu",$contfenqu);
        $this->assign("contbrand",$contbrand);
        $this->assign("contgys",$contgys);
        $this->assign("feiyongs",$feiyongs);
        $contfeiyong=count($feiyongs);
        $this->assign("contfeiyong",$contfeiyong);
        $this->assign("applyde",$applyde);
        $btn=$this->getbton(12,$aid);
        $this->assign("btn",$btn);
        $logs=$this->getlog(12,$aid);
        //print_r($logs);
        $this->assign("logs",$logs);
        return $this->fetch();
    }

      //取消处理
    public function quxiaochuli(){
    		$request = Request::instance();

    	
    	$data=$request->post();

    	if($data){
    		$aid=$data["aid"];
    		//print_r($data);exit;
    		//获得单据中现存的单子
    		$all=Db::table("ap_apply_detail")->where(["apply_id"=>$data['aid'],"is_deleted"=>0])->select();
    		$jishu=0;$qx=[];$did=[];
    		for($i=0;$i<count($data["did"]);$i++){
    			if(trim($data["quxiaoyuanyin"][$i])){
    				$qx[]=["id"=>$data["did"][$i],"yuanyin"=>$data["quxiaoyuanyin"][$i]];
    				$jishu++;
    				$did[]=$data["did"][$i];
    			}
    		}
    		//print_r($qx);exit;
    		if(!$jishu){
    			return json_encode(["msg"=>"至少删除一条明细","state"=>2]);
    		}
    		
    			Db::startTrans();
    		try{
    				    		//原单
	    		$apply=Db::table("ap_apply")->where(["id"=>$aid])->find();
	    		
	    		//生成单号
	    		 $timenow=date("Ymd");
	       		$num=Db::table("ap_apply")->where("no like '$timenow%'")->count();
	      		 $num++;
	      		 $strnum=$timenow.sprintf("%05d", $num);
	      		 $addapply=$apply;
	      		 unset($addapply["id"]);
	      		 $addapply["no"]=$strnum;$addapply["created_on"]=date("Y-m-d H:i:s");$addapply["modifiled_on"]=null;
				$addapply["yuan_id"]=$aid;
				$addapply["state"]=1;
				$addapply["annex_id"]=$data["attach"];
				$addapply["is_actived"]=0;$addapply["is_shengxiao"]=0;$addapply["guidangdate"]=null;
				$addapply["tag"]=0;$addapply["c_users_id"]=Session::get("login_id");
				//print_r($addapply);exit;
				$res1=Db::table("ap_apply")->insertGetId($addapply);
    			$removedata=[];
	    		for($i=0;$i<count($all);$i++){
	    			for($j=0;$j<count($qx);$j++){
	    				//echo $all[$i]["id"]."---".$qx[$j]["id"]."|";
	    				if($all[$i]["id"]==$qx[$j]["id"]){
	    					$tmp=$all[$i];
	    					$tmp["yuanmingxi"]=$tmp["id"];
	    					$tmp["biandongyuanyin"]=$qx[$j]["yuanyin"];
	    			
	    					$tmp["modifiled_on"]=date("Y-m-d H:i:s");
	    					$tmp["apply_id"]=$res1;
	    					$tmp["tag"]=2;
	    					 unset($tmp["id"]);
	    					 $removedata[]=$tmp;
	    					 //echo 1;
	    				}
	    			}
	    		}
	    		//print_r($removedata);exit;
				//插入新明细
				$res2=Db::table("ap_apply_detail")->insertAll($removedata);
				//原明细取消
				$str=implode(',',$did);
				//$res3=1;
				$res3=Db::table("ap_apply_detail")->where("id in($str)")->update(["is_actived"=>0]);
				
				$res4=Db::table("ap_apply")->where(["id"=>$aid])->update(["isqxyd"=>1]);
				
    		}catch(\Exception $e){
	        	//echo $e->getMessage();
	        	Db::rollBack();
	           return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }
	         if($res1&&$res2&&$res3&&$res4){

                
                if($data["state"]==3){
                    $jieguo=$this->gowork(12,$res1);
                    if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                        Db::commit();
                        return $jieguo;
                    }else{
                        Db::rollBack();
                        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                    }
                }else{
                    Db::commit();
            

                    return json_encode(["msg"=>"","state"=>1]);
                }
				
	        }else{
	        	Db::rollBack();
	          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }

    	}else{
    		return json_encode(["msg"=>"请正确提交","state"=>2]);
    	}
    }
     //删除取消草稿
    public function shanchuqx($aid){
    	//
    	$yuan=Db::table("ap_apply")->where(["id"=>$aid])->find();
    	$yuanid=$yuan["yuan_id"];
    	$yuande=Db::table("ap_apply_detail")->where(["apply_id"=>$aid])->field("yuanmingxi")->select();
    	$yuandelist=[];

    	for($i=0;$i<count($yuande);$i++){
    		$yuandelist[]=$yuande[$i]["yuanmingxi"];
    	}
    	//return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
    	$str=implode(',',$yuandelist);
    	
    	try{
    		//恢复旧单
    		Db::table("ap_apply")->where(["id"=>$yuanid])->update(["tag"=>0,"isqxyd"=>0]);
    		$res2=Db::table("ap_apply")->where(["id"=>$aid])->update(["is_deleted"=>1]);
    		//恢复旧单明细
    		$res1=Db::table("ap_apply_detail")->where("id in ($str)")->update(["is_actived"=>1]);
    	}catch(\Exception $e){
	        	//echo $e->getMessage();
	        	Db::rollBack();
	           return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }
	         if($res1&&$res2){

				Db::commit();
			

	            return json_encode(["msg"=>"","state"=>1]);
	        }else{
	        	Db::rollBack();
	          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }
    }
    //反馈
    public function fankui($aid,$rt=0){
    	$this->assign("aid",$aid);
    	$apply=Db::table("ap_apply")->alias("ap")
    	->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
    	->join("ap_apply next","ap.next_id=next.id","LEFT")
    	->join("ti_state s","ap.state=s.id")
    	 ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
      
    	->where(["ap.id"=>$aid,"de.index"=>1])
    	->field("ap.title,ap.no,yuan.no as yuanno,next.no as nextno,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.created_on")
    	->find();
    	$this->assign("apply",$apply);
    		$contfenqu=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid and fankui_id=0")->count("distinct fenqu");
    	$contbrand=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid and fankui_id=0")->count("distinct brand");
    	$contgys=Db::table("ap_apply_detail")->where("is_actived=1 and is_deleted=0 and apply_id=$aid and fankui_id=0")->count("distinct gys");
    	$feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge,sum(apd.zong_xiaoliang) as xiaoliangs from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid and fankui_id=0 group by k3.id,k3.title");
    	$this->assign("contfenqu",$contfenqu);
    	$this->assign("contbrand",$contbrand);
    	$this->assign("contgys",$contgys);
    	$this->assign("feiyongs",$feiyongs);
    	$contfeiyong=count($feiyongs);
    	$this->assign("contfeiyong",$contfeiyong);
    	$contzonge=0;$contzongxiao=0;
    	for($i=0;$i<count($feiyongs);$i++){
    		$contzonge+=$feiyongs[$i]["kezonge"];
    		$contzongxiao+=$feiyongs[$i]["xiaoliangs"];
    	}
    	$contzonge=round($contzonge,2);
    	$contzongxiao=round($contzongxiao,2);
		$this->assign("contzonge",$contzonge);
    	$this->assign("contzongxiao",$contzongxiao);
    	$applyde=Db::table("ap_apply_detail")->alias("apd")
    		->join("ap_apply ap","apd.apply_id=ap.id")
    		->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    		->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    		->join("cg_market_city c","apd.shi=c.id","LEFT")
    		->join("cg_jxs j","apd.jxs=j.id","LEFT")
    		->join("cg_system s","apd.system=s.id","LEFT")
    		->join("cg_net n","apd.net=n.id","LEFT")
    		->join("pro_brands pb","apd.brand=pb.id","LEFT")
    		->join("pro_category pc","apd.category=pc.id","LEFT")
    		->join("pro_series ps","apd.series=ps.id","LEFT")
    		->where("apd.is_actived=1 and apd.is_deleted=0 and apd.apply_id=$aid and apd.fankui_id=0")
    		->group("z.title,p.title,c.title,j.title,s.title,n.title,pb.brand_name,z.id,p.id,c.id,j.id,s.id,n.id,pb.id")
    		->field("z.title as fenqu,z.id as fenquid,p.title as sheng,p.id as shengid,c.title as shi,c.id as shiid,j.title as jxs,j.id as jxsid,s.title as system,s.id as systemid,n.title as net,n.id as netid,pb.brand_name as brand,pb.id as brandid,sum(pifuzonge+pifuzonge*shuilv/100) as pifuzonges,sum(zong_xiaoliang) as zong_xiaoliangs")
    		->select();
    	//print_r($applyde);exit;
        for($i=0;$i<count($applyde);$i++){
            $applyde[$i]["yujifeiyonglv"]=$applyde[$i]["pifuzonges"]/$applyde[$i]["zong_xiaoliangs"]*100;
        }
    	$this->assign("applyde",$applyde);
    	$this->assign("rt",$rt);
    	return $this->fetch();
	
    }
    //反馈处理
    public function fankuichuli(){
    	$request = Request::instance();
    	$data=$request->post();
    	if($data){
    		//print_r($data);exit;
    		$aid=$data["aid"];
    		//筛选反馈
    		$fklist=[];
    		for($i=0;$i<count($data["fenqu"]);$i++){
    			if(trim($data["fankuixiaoliang"][$i])){
    				$fklist[]=["fenqu"=>$data["fenqu"][$i],"sheng"=>$data["sheng"][$i],"shi"=>$data["shi"][$i],"jxs"=>$data["jxs"][$i],
    					"system"=>$data["system"][$i],"net"=>$data["net"][$i],"brand"=>$data["brand"][$i],"fankuixiaoliang"=>$data["fankuixiaoliang"][$i],
    					"fankuiremark"=>$data["fankuiremark"][$i]
    				];
    			}
    		}
    		//print_r($fklist);exit;
    		if(!$fklist)
    			return json_encode(["msg"=>"至少反馈一条明细","state"=>2]);
    		Db::startTrans();
    		try{
    			//创建反馈表
    			//生成单号
               $title=Db::table("ap_apply")->where("id=$aid")->value("title");
	    		 $timenow=date("Ymd");
	       		$num=Db::table("ap_fankui")->where("no like '$timenow%'")->count();
	      		 $num++;
	      		 $strnum=$timenow.sprintf("%05d", $num);
	      		 $adddata=["no"=>$strnum,"created_on"=>date("Y-m-d H:i:s"),"c_users_id"=>Session::get("login_id"),"state"=>1,"remark"=>$data["remark"],"fujian"=>$data["attach"],"title"=>$title];
	      		 //print_r($adddata);exit;
	      		 $res1=Db::table("ap_fankui")->insertGetId($adddata);
    			for($i=0;$i<count($fklist);$i++){
    				$where="apply_id=$aid and is_actived=1 and is_deleted=0 and fankui_id=0 and fenqu={$fklist[$i]["fenqu"]} and brand={$fklist[$i]["brand"]} ";
    			
    				if($fklist[$i]["sheng"])
    					$where.="and sheng={$fklist[$i]["sheng"]} ";
    				else
    					$where.="and sheng is null ";
    				if($fklist[$i]["shi"])
    					$where.="and shi={$fklist[$i]["shi"]} ";
    				else
    					$where.="and shi is null ";
    				if($fklist[$i]["jxs"])
    					$where.="and jxs={$fklist[$i]["jxs"]} ";
    				else
    					$where.="and jxs is null ";
    				if($fklist[$i]["system"])
    					$where.="and system={$fklist[$i]["system"]} ";
    				else
    					$where.="and system is null ";
    				if($fklist[$i]["net"])
    					$where.="and net={$fklist[$i]["net"]} ";
    				else
    					$where.="and net is null ";
    				//exit;
    				$zongxiaoliang=Db::table("ap_apply_detail")->where($where)->sum("zong_xiaoliang");
    				$bili=$fklist[$i]["fankuixiaoliang"]/$zongxiaoliang;
    				//echo "update ap_apply_detail set fankuiremark='{$fklist[$i]["fankuiremark"]}',fankuixiaoliang=zong_xiaoliang*{$bili},fankui_id=$res1 where {$where}";exit;
    				Db::table("ap_apply_detail")->query("update ap_apply_detail set fankuiremark='{$fklist[$i]["fankuiremark"]}',fankuixiaoliang=zong_xiaoliang*{$bili},fankui_id=$res1 where {$where}");
    				Db::table("ap_apply")->where(["id"=>$aid])->update(["is_fankui"=>1]);
    			}
    		}catch(\Exception $e){
	        	//echo $e->getMessage();
	        	Db::rollBack();
	           return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }
            if($data["state"]==3){
                $jieguo=$this->gowork(14,$res1);
                if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                    Db::commit();
                    return $jieguo;
                }else{
                    Db::rollBack();
                    return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
            }else{
                Db::commit();
                return json_encode(["msg"=>"","state"=>1]);
            }
	        	
    	}else{
    		 return json_encode(["msg"=>"请正确提交","state"=>2]);
    	}

    }
    //核销
    public function hexiao($aid,$type=0){
    	$this->assign("aid",$aid);$this->assign("type",$type);
    	$where="ap.id=$aid and apd.is_deleted=0 ";
    	switch ($type) {
    		case 0:
    			#可核销
    			$where.="and apd.buyu_he=0 and apd.hexiao<apd.pifuzonge+apd.pifuzonge*shuilv/100 and apd.fankui_id>0";
    			break;
    		case 2:
    			#不予核销
    			$where.="and apd.buyu_he=1 and apd.fankui_id<>0";
    			break;
    		case 1:
    			#核销中
    			$where.="and apd.is_hexiao<>0 and apd.fankui_id<>0";
    			break;
    		case 3:
    			#未反馈
    			$where.="and apd.fankui_id=0";
    			break;
    		default:
    			# code...
    			break;
    	}
    	$ade=Db::table("ap_apply_detail")->alias("apd")
    	->join("ap_apply ap","apd.apply_id=ap.id")
    	 ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    	->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    	->join("cg_market_city c","apd.shi=c.id","LEFT")
    	->join("cg_jxs j","apd.jxs=j.id","LEFT")
    	->join("cg_system s","apd.system=s.id","LEFT")
    	->join("cg_net n","apd.net=n.id","LEFT")
    	->join("pro_brands pb","apd.brand=pb.id","LEFT")
    	->join("pro_category pc","apd.category=pc.id","LEFT")
    	->join("pro_series ps","apd.series=ps.id","LEFT")
    	->join("cg_channel_types1 ct","ap.channel_id=ct.id")
    	->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    	->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    	->join("gys g","apd.gys=g.id")
    	->join("cg_paymethod cp","apd.zfid=cp.id")
    	->where($where)
    	->order("apd.id")
    	->field("apd.id,ap.no,apd.detail_no,ec.em_name as cname,ct.title as channel,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.zong_xiaoliang,apd.fankuixiaoliang,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as zongjine,apd.hexiao,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100)-apd.hexiao as weihe,apd.zfid,apd.start_time,ap.id as apid")
    	->select();
    	  $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);
    	$this->assign("ade",$ade);
    	return $this->fetch();
    }
    //获取单挑明细信息
    public function dantiaomingxi($did){
    	$res=Db::table("ap_apply_detail")->where(["id"=>$did])
    	->field("(pifuzonge+pifuzonge*shuilv/100) as fankuijine,hexiao,((pifuzonge+pifuzonge*shuilv/100)-hexiao) as weihe")->find();
    	return json_encode($res);

    }
    //不予核销
    public function nohexiao($did,$state){
    	Db::startTrans();
    	try{
    		Db::table("ap_apply_detail")->where(["id"=>$did])->update(["buyu_he"=>$state]);
    	}catch(\Exception $e){
	        	//echo $e->getMessage();
	        	Db::rollBack();
	           return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	    }
    	
    	return json_encode(["msg"=>"","state"=>1]);

    }
    //设置发票信息
    public function setfapiao(){
    		 //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);

    	return $this->fetch();
    }
     //核销预览
    public function hexiaoscan(){
    	$request = Request::instance();

    	
    	$data=$request->post();
    	//print_r($data);
    	$this->assign("zongbeizhu",$data["zongbeizhu"]);
    		//处理接收数据
    	$postdata=[];
    	for($i=0;$i<count($data["dids"]);$i++){
    		$postdata[$i]=["did"=>$data["dids"][$i],"isfa"=>$data["isfa"][$i],
    		"fapiao"=>$data["fapiao"][$i],"shuilv"=>$data["shuilv"][$i],"isdi"=>$data["isdi"][$i],
    		"weishui"=>$data["weishui"][$i],"shuijin"=>$data["shuilv"][$i]*$data["weishui"][$i]/100,
    		"hanshui"=>$data["shuilv"][$i]*$data["weishui"][$i]/100+$data["weishui"][$i],"beizhu"=>$data["beizhu"][$i],"zfid"=>$data["zfid"][$i]
    		];
    	}

    	$this->assign("postdata",$postdata);
    	$eid=Session::get("employee_id");$aid=$data["aid"];
    	$user=Db::table("employee")->alias("e")
    	->join("job_employee je","e.id=je.employee_id","LEFT")
    	->join("job j","je.job_id=j.id","LEFT")
    	->join("department_employee de","e.id=de.employee_id","LEFT")
    	->join("department d","de.department_id=d.id","LEFT")
    	->where(["e.id"=>$eid,"de.index"=>1,"d.is_actived"=>1,"d.is_deleted"=>0,"j.is_actived"=>1,"j.is_deleted"=>0])
    	->field("e.id,e.em_name,d.de_name,j.job_name")
    	->find();
    	$this->assign("user",$user);
    	$time=date("Y-m-d H:i");
    	$this->assign("time",$time);
		$apply=Db::table("ti_apply")->alias("ap")
        ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
    	->where(["ap.id"=>$aid])->field("ec.em_name as cname")->find();
$this->assign("apply",$apply);

    	$dids=implode(',',$data["dids"]);
    	$ade=Db::table("ap_apply_detail")->alias("apd")
    	->join("ap_apply ap","apd.apply_id=ap.id")
    	 ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    	->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    	->join("cg_market_city c","apd.shi=c.id","LEFT")
    	->join("cg_jxs j","apd.jxs=j.id","LEFT")
    	->join("cg_system s","apd.system=s.id","LEFT")
    	->join("cg_net n","apd.net=n.id","LEFT")
    	->join("pro_brands pb","apd.brand=pb.id","LEFT")
    	->join("pro_category pc","apd.category=pc.id","LEFT")
    	->join("pro_series ps","apd.series=ps.id","LEFT")
    	->join("cg_channel_types1 ct","ap.channel_id=ct.id")
    	->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    	->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    	->join("gys g","apd.gys=g.id")
    	->join("cg_paymethod cp","apd.zfid=cp.id")
    	->where("ap.id=$aid and apd.id in($dids)")
    	->order("apd.id")
    	->field("apd.id,ap.no,apd.detail_no,ec.em_name as cname,ct.title as channel,g.gys_name,z.title as fenqu,p.title as sheng,c.title as shi,j.title as jxs,s.title as system,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,k3.title as kemu3,apd.zong_xiaoliang,apd.fankuixiaoliang,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as zongjine,apd.hexiao,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100)-apd.hexiao as weihe,apd.zfid,apd.start_time,ap.id as apid")
    	->select();
    	
    	$this->assign("ade",$ade);
    	   $datastr=json_encode($data);
        $this->assign("datastr",$datastr);
         $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);
    	return $this->fetch();
    }
     //核销提交处理
    public function hexiaochuli(){
    	$request = Request::instance();
    	$data=$request->post();
    	$formdata=json_decode($data["form-data"],true);

    	//print_r($formdata);exit;
    	$aid=$formdata["aid"];
    	$buhelist=[];
    	if(isset($formdata["yuebuhe"])){
    		$buhelist=$formdata["yuebuhe"];
    	}
    	Db::startTrans();
    	try{
    		//生成核销主表数据
    		
    		$timenow=date("Ymd");
			$num=Db::table("ap_hexiao_apply")->where("no like '$timenow%'")->count();
			$num++;
			$strnum=$timenow.sprintf("%04d", $num);
			if(isset($data["isgui"]))
				$isgui=1;
			else
				$isgui=0;
			$he_app_data=[
				"no"=>$strnum,"c_user_id"=>Session::get("login_id"),"created_on"=>date("Y-m-d H:i:s"),"state"=>1,"fujian"=>$data["attach"],"remark"=>$data["remark"],
				"notice"=>$isgui,"apply_id"=>$aid
			];
			//print_r($he_app_data);exit;
			$res1=Db::table("ap_hexiao_apply")->insertGetId($he_app_data);
			//插入明细
			$detail=[];
			for($i=0;$i<count($formdata["dids"]);$i++){
				$tmp["hexiao_id"]=$res1;$tmp["detail_id"]=$formdata["dids"][$i];$tmp["he_detail_no"]=$i+1;
				$tmp["hexiao_weishui"]=$formdata["weishui"][$i];$tmp["hexiao_shuilv"]=$formdata["shuilv"][$i];
				$tmp["has_fp"]=$formdata["isfa"][$i];$tmp["fp_no"]=$formdata["fapiao"][$i];
				$tmp["dikou"]=$formdata["isdi"][$i];$tmp["zfid"]=$formdata["zfid"][$i];
				$tmp["beizhu"]=$formdata["beizhu"][$i];
				$tmp["bu_state"]=$formdata["bu_state"];
				if(in_array($tmp["detail_id"],$buhelist)){
					$buyu_he=1;
				}else{
					$buyu_he=0;
				}
				$tmp["buyu_he"]=$buyu_he;
				$detail[]=$tmp;
				Db::table("ap_apply_detail")->query("update ap_apply_detail set is_hexiao=1,buyu_he=$buyu_he,hexiao=hexiao+{$formdata["weishui"][$i]} where id={$tmp["detail_id"]}");
			}
			//print_r($detail);exit;
			$res2=Db::table("ap_hexiao_detail")->insertAll($detail);
			//
			
			$res3=Db::table("ap_apply")->where(["id"=>$aid])->update(["is_hexiao"=>1,"modifiled_on"=>date("Y-m-d H:i:s")]);

    	}catch(\Exception $e){
	        	//echo $e->getMessage();
	        	Db::rollBack();
	           return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	    }
	     if($res1&&$res2&&$res3){
                if($data["state"]==3){
                     $jieguo=$this->gowork(15,$res1);
                    if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                        Db::commit();
                        return $jieguo;
                    }else{
                        Db::rollBack();
                        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                    }
                }else{
                    Db::commit();
                    return json_encode(["msg"=>"","state"=>1]);
                }
               

			
	        }else{
	        	Db::rollBack();
	          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
	        }

    }
   
    public function hxshanchu($id){
        Db::startTrans();
        try{
             $arr=Db::table("ap_hexiao_detail")->where(["hexiao_id"=>$id])->select();
            for($i=0;$i<count($arr);$i++){
                $tmp=Db::table("ap_apply_detail")->where(["id"=>$arr[$i]["detail_id"]])->find();
                $upde["id"]=$arr[$i]["detail_id"];
                $upde["hexiao"]=$tmp["hexiao"]-$arr[$i]["hexiao_weishui"];
                if($arr[$i]["buyu_he"])
                    $upde["buyu_he"]=0;
                Db::table("ap_apply_detail")->update($upde);
            }
            Db::table("ap_hexiao_apply")->where(["id"=>$id])->update(["is_deleted"=>1]);
        }catch(\Exception $e){
                //echo $e->getMessage();
                Db::rollBack();
               return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
        }
       
          Db::commit();
           return json_encode(["msg"=>"","state"=>1]);

    }
	//产品弹框
	public function selectBrands(){
		return $this->fetch();
	}
	//产品类框
	public function selectCategory(){
		return $this->fetch();
	}
	//产品系列框
	public function selectSeries(){
		return $this->fetch();
	}
	
	//费用科目3列框
	public function selectFeiyong(){
		$esuseway = $this->request->param('esuseway');
		$channel = $this->request->param('channel');
		$this->assign("esuseway",$esuseway);
		$this->assign("channel",$channel);
		return $this->fetch();
	}

	//费用科目3数据
	public function feiyong3json(){
		$esuseway = $this->request->param('esuseway');
		$channel = $this->request->param('channel');
        $where = [];
        if($esuseway){
            $where['esuseway'] = ['like','%"'.$esuseway.'"%'];
            $where["channeltypes"]=['like','%"'.$channel.'"%'];
        }
        $data = Db::table('cg_feiyongkemu3')->field('title,id')->where($where)->select();
//        echo Db::table('cg_feiyongkemku3')->getLastSql();
        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
	}
	//费用3树
	public function feiyong3(){
		$esuseway = $this->request->param('esuseway');
		$channel = $this->request->param('channel');
        $where = [];
        if($esuseway){
            $where['esuseway'] = ['like','%"'.$esuseway.'"%'];
            $where["channeltypes"]=['like','%"'.$channel.'"%'];
        }
        $data = Db::table('cg_feiyongkemu3')->field('title as name,id')->where($where)->select();
        return json_encode($data);

	}
	 //suggest查找供应商
    public function gysjson(){
        $data = Db::table('gys')->field('gys_name as title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
	 //suggest查找分区
    public function fenqujson(){
        $data = Db::table('cg_market_zoning')->field('title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
    //suggest查找省
    public function shengjson(){
        $data = Db::table('cg_market_provice')->field('title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
     //suggest查找市
    public function shijson(){
        $data = Db::table('cg_market_city')->field('title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
     //suggest查找经销商
    public function jxsjson(){
        $data = Db::table('cg_jxs')->field('title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
       //suggest查找系统
    public function xtjson(){
        $data = Db::table('cg_system')->field('title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
       //suggest查找网点
    public function wangdianjson(){
        $data = Db::table('cg_net')->field('title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
    //分区列表
    public function selectFenqu(){
    	return $this->fetch();
    }
     //省列表
    public function selectSheng(){
    	return $this->fetch();
    }
        //市列表
    public function selectShi(){
    	return $this->fetch();
    }
         //经销商列表
    public function selectJxs(){
    	return $this->fetch();
    }
      //系统列表
    public function selectXt(){
    	return $this->fetch();
    }
       //系统网点列表
    public function selectWangdian(){
    	return $this->fetch();
    }
        //供应商列表
    public function selectGys(){
    	return $this->fetch();
    }
    //经销商树
    public function jxstree(){
    	$data = Db::table('cg_jxs')->field('title as name,id')->select();
    	 return json_encode($data);
    }
    //分区树
    public function fenqutree(){
    	$data = Db::table('cg_market_zoning')->field('title as name,id')->select();
    	 return json_encode($data);
    }
     //省树
    public function shengtree(){
    	$data=[];
    	$res1 = Db::table('cg_market_zoning')->field('title as name,id')->select();
    	for($i=0;$i<count($res1);$i++){
    		 	$data[$i]["id"]="B".$res1[$i]["id"];
               
                $data[$i]["name"]=$res1[$i]["name"];
                $data[$i]["pId"]=0;
                $data[$i]["nocheck"]=true;
    	}
    	$res2=Db::table("cg_market_provice")->field("title as name,id,zoning as pid")->select();
    	  for($i=0;$i<count($res2);$i++){
             
                $data[$i+count($res1)]["id"]=$res2[$i]["id"];
               
                 $data[$i+count($res1)]["name"]=$res2[$i]["name"];
                $data[$i+count($res1)]["pId"]="B".$res2[$i]["pid"];
               
                
           }
    	 return json_encode($data);
    	
    }
    //市树
    public function shitree(){
    	$data=[];
    	$res1 = Db::table('cg_market_zoning')->field('title as name,id')->select();
    	for($i=0;$i<count($res1);$i++){
    		 	$data[$i]["id"]="B".$res1[$i]["id"];
               
                $data[$i]["name"]=$res1[$i]["name"];
                $data[$i]["pId"]=0;
                $data[$i]["nocheck"]=true;
    	}
    	$res2=Db::table("cg_market_provice")->field("title as name,id,zoning as pid")->select();
    	  for($i=0;$i<count($res2);$i++){
             
                $data[$i+count($res1)]["id"]="S".$res2[$i]["id"];
               
                 $data[$i+count($res1)]["name"]=$res2[$i]["name"];
                $data[$i+count($res1)]["pId"]="B".$res2[$i]["pid"];
                $data[$i+count($res1)]["nocheck"]=true;
                
           }
        $res3=Db::table("cg_market_city")->field("title as name,id,provice as pid")->select();
          for($i=0;$i<count($res3);$i++){
             
              $data[]=["id"=>$res3[$i]["id"],"name"=>$res3[$i]["name"],"pId"=>"S".$res3[$i]["pid"]];
                
           }
    	 return json_encode($data);
    	
    }
   // 系统树
    public function xttree(){
    	$data=[];
    	$res1= Db::table('cg_jxs')->field('title as name,id')->select();
    	for($i=0;$i<count($res1);$i++){
             
              $data[]=["id"=>"J".$res1[$i]["id"],"name"=>$res1[$i]["name"],"pId"=>"0","nocheck"=>true];
                
           }
        $res2= Db::table('cg_system')->field('title as name,id,jxs as pid')->select();
          for($i=0;$i<count($res2);$i++){
             
              $data[]=["id"=>$res2[$i]["id"],"name"=>$res2[$i]["name"],"pId"=>"J".$res2[$i]["pid"]];
                
           }
         return json_encode($data);
    }
     // 网点树
    public function wangdiantree(){
    	$data=[];
    	$res1= Db::table('cg_jxs')->field('title as name,id')->select();
    	for($i=0;$i<count($res1);$i++){
             
              $data[]=["id"=>"J".$res1[$i]["id"],"name"=>$res1[$i]["name"],"pId"=>"0","nocheck"=>true];
                
           }
        $res2= Db::table('cg_system')->field('title as name,id,jxs as pid')->select();
          for($i=0;$i<count($res2);$i++){
             
              $data[]=["id"=>"X".$res2[$i]["id"],"name"=>$res2[$i]["name"],"pId"=>"J".$res2[$i]["pid"],"nocheck"=>true];
                
           }
            $res3= Db::table('cg_net')->field('title as name,id,system_id as pid')->select();
             for($i=0;$i<count($res3);$i++){
             
              $data[]=["id"=>$res3[$i]["id"],"name"=>$res3[$i]["name"],"pId"=>"X".$res3[$i]["pid"]];
                
           }
         return json_encode($data);
    }
      //供应商树
    public function gystree(){
    	$data = Db::table('gys')->field('gys_name as name,id')->select();
    	 echo json_encode($data);
    }
    //Ap需反馈
    public function apRtLeft(){
	//获取类型列表
    	$states=Db::table("ti_state")->order("paixu")->select();
    	$this->assign("states",$states);
    	$request = Request::instance();

    	$eid=Session::get("login_id");
    	$data=$request->post();
    	$where="ap.is_deleted=0 and  apd.is_deleted=0 and apd.fankui_id=0 and apd.is_actived=1 and ap.tag=0 and ap.state=7 and ap.is_shengxiao=1 and ap.c_users_id=$eid ";
    	if($data){
    		if($data["no"])
    			$where.="and ap.no={$data["no"]} ";
    		if(trim($data["title"]))
    			$where.="and ap.title like '%{$data["title"]}%' ";
    		if($data["state"])
    			$where.="and ap.state={$data["state"]} ";
    		if(trim($data["start"]))
    			$where.="and ap.created_on>='{$data["start"]} 00:00:00' ";
    		if(trim($data["end"]))
    			$where.="and ap.created_on<='{$data["end"]} 23:59:59' ";
    	}else{
    		$data=["no"=>"","title"=>"","state"=>"","start"=>"","end"=>""];
    	}

    	$applys=Db::table("ap_apply")->alias("ap")
    	->join("ap_apply yuan","ap.yuan_id=yuan.id","LEFT")
    	->join("ti_state s","ap.state=s.id")
    	 ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("ap_apply_detail apd","ap.id=apd.apply_id","LEFT")
    	->where($where)
    	->group("ap.id,apd.apply_id")
    	->order("ap.created_on desc")
    	->field("ap.id,ap.is_actived,ap.no,ap.title,s.title as zhuangtai,ec.em_name as cname,ap.created_on,ap.state,ap.yuan_id,ap.next_id,ap.is_shengxiao,ap.is_fankui,ap.tag,ap.is_hexiao,yuan.tag as yuantag")
    	->select();
    	//echo Db::table("ap_apply")->getLastSql();
    	$this->assign("applys",$applys);
    	
    	$this->assign("data",$data);
		return $this->fetch();
    }
    //反馈报告
    public function apRtRight($page=1,$list=10){
        $states=Db::table("ti_state")->order("paixu")->select();
        $this->assign("states",$states);
        $request = Request::instance();

        $eid=Session::get("login_id");
        $data=$request->post();
        $where="ap.is_actived=1 and ap.is_deleted=0 and c_users_id=$eid ";
        if($data){
            if($data["no"])
                $where.="and ap.no={$data["no"]} ";
            
            if($data["state"])
                $where.="and ap.state={$data["state"]} ";
            if(trim($data["start"]))
                $where.="and ap.created_on>='{$data["start"]} 00:00:00' ";
            if(trim($data["end"]))
                $where.="and ap.created_on<='{$data["end"]} 23:59:59' ";
        }else{
            $data=["no"=>"","state"=>"","start"=>"","end"=>""];
        }
        $sum=Db::table("ap_fankui")->alias("ap")
        ->where($where)->count();
        $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
        $apply=Db::table("ap_fankui")->alias("ap")
        ->where($where)->order("ap.id desc")->limit($start,$list)->select();
        for($i=0;$i<count($apply);$i++){
            $tmp=Db::table("ap_apply_detail")->where(["fankui_id"=>$apply[$i]["id"]])->find();
            $apply[$i]["aid"]=$tmp["apply_id"];
            //$apply[$i]["title"]=Db::table("ap_apply")->where(["id"=>$tmp["apply_id"]])->value("title");
            $apply[$i]["statetype"]=Db::table("ti_state")->where(["id"=>$apply[$i]["state"]])->value("title");
            $apply[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$apply[$i]["id"],"ywlx"=>14])->value("id");
            $apply[$i]["cuser"]=Db::table("users")->alias("u")->join("employee e","u.employee_id=u.id")->value("em_name");
        }
        $this->assign("apply",$apply);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);
        $this->assign("data",$data);
    	return $this->fetch();
    }
    public function fkbaocunchuli(){
        $request = Request::instance();
        $data=$request->post();

        //print_r($data);exit;
        for($i=0;$i<count($data["did"]);$i++){
            if(!$data["did"][$i])
                return json_encode(["msg"=>"请正确提交","state"=>2]);
            if(!$data["fankuixiaoliang"][$i])
                return json_encode(["msg"=>"反馈销量不能为0","state"=>2]);
        }
        $fid=14;$aid=$data["fkid"];
        $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
        if($res["operateStatus"]=="success"){
             Db::startTrans();
            try{
                for($i=0;$i<count($data["did"]);$i++){
                    Db::table("ap_apply_detail")->where(["id"=>$data["did"][$i]])->update(["fankuixiaoliang"=>$data["fankuixiaoliang"][$i]]);
                }
                Db::table("ap_fankui")->where("id=$aid")->update(["state"=>3]);
            }catch (\Exception $e){
                        //return $e->getMessage();
                Db::rollBack();
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            return json_encode(["msg"=>"","state"=>1]);
        }else{
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
    }
    public function fkxiugai(){
        $request = Request::instance();
        $data=$request->post();

        //print_r($data);exit;
        for($i=0;$i<count($data["did"]);$i++){
            if(!$data["did"][$i])
                return json_encode(["msg"=>"请正确提交","state"=>2]);
            if(!$data["fankuixiaoliang"][$i])
                return json_encode(["msg"=>"反馈销量不能为0","state"=>2]);
        }
        Db::startTrans();
        try{
            for($i=0;$i<count($data["did"]);$i++){
                Db::table("ap_apply_detail")->where(["id"=>$data["did"][$i]])->update(["fankuixiaoliang"=>$data["fankuixiaoliang"][$i]]);
            }
        }catch (\Exception $e){
                    //return $e->getMessage();
            Db::rollBack();
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
        if($data["state"]==3){
            $jieguo=$this->gowork(14,$data["fkid"]);
                if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                    Db::commit();
                    return $jieguo;
                }else{
                    Db::rollBack();
                    return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
        }else{
            Db::commit();
             return json_encode(["msg"=>"","state"=>1]);
        }
    }
    public function fkup($aid,$fkid,$from=1){
        $this->assign("from",$from);
        $this->assign("fkid",$fkid);$this->assign("aid",$aid);
        $apply=Db::table("ap_apply")->where(["id"=>$aid])->find();

        $this->assign("apply",$apply);

        $fk=Db::table("ap_fankui")->alias("fk")
        ->join("ti_state s","fk.state=s.id")
        ->join("users uc","fk.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
        ->where(["fk.id"=>$fkid,"de.index"=>1])
        ->field("fk.id,fk.no,ec.em_name as cname,d.de_name,fk.remark,fk.state,fk.is_shengxiao")
        ->find();
        $this->assign("fk",$fk);

        $fkde=Db::table("ap_apply_detail")->alias("apd")
        ->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
        ->join("cg_market_provice p","apd.sheng=p.id","LEFT")
        ->join("cg_market_city c","apd.shi=c.id","LEFT")
        ->join("cg_jxs j","apd.jxs=j.id","LEFT")
        ->join("cg_system s","apd.system=s.id","LEFT")
        ->join("cg_net n","apd.net=n.id","LEFT")
        ->join("pro_brands pb","apd.brand=pb.id","LEFT")
        ->join("pro_category pc","apd.category=pc.id","LEFT")
        ->join("pro_series ps","apd.series=ps.id","LEFT")
        ->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
        ->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
        ->join("gys g","apd.gys=g.id")
        ->join("cg_paymethod cp","apd.zfid=cp.id")
        ->where("apd.is_actived=1 and apd.is_deleted=0 and apd.fankui_id=$fkid and apd.isok=1")
        ->field("apd.id,apd.detail_no,g.no as gys_no,g.gys_name,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,apd.start_time,apd.end_time,k3.title as kemu3,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,zong_xiaoliang,apd.fankuixiaoliang")
        ->select();
        //echo Db::table("ap_apply_detail")->getLastSql();
        //print_r($fkde);
        for($i=0;$i<count($fkde);$i++){
            $fkde[$i]["yujifeiyonglv"]=$fkde[$i]["hanshui"]/$fkde[$i]["zong_xiaoliang"]*100;
           $fkde[$i]["shijifeiyonglv"]=$fkde[$i]["hanshui"]/$fkde[$i]["fankuixiaoliang"]*100; 
        }
        $this->assign("fkde",$fkde);

        $all=Db::table("ap_apply_detail")->alias("apd")
        ->where("apd.is_actived=1 and apd.is_deleted=0 and apd.fankui_id=$fkid")
        ->group("apd.fankui_id")
        ->field("sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,sum(zong_xiaoliang) as zong_xiaoliang,sum(fankuixiaoliang) as fankuixiaoliang,sum(pifuzonge) as pifuzonges")
        ->find();
        $this->assign("all",$all);
        $feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge,sum(apd.zong_xiaoliang) as xiaoliangs from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid  group by k3.id,k3.title");
        $this->assign("feiyongs",$feiyongs);
        $contfeiyong=count($feiyongs);
        $this->assign("contfeiyong",$contfeiyong);
          $logs=$this->getlog(14,$fkid);
        //print_r($logs);
        $this->assign("logs",$logs);
        if($fk["state"]==2){
            $btn=$this->getbton(14,$fkid);
            $this->assign("btn",$btn);
        }
        return $this->fetch();

    }
    public function fkzuofeichuli(){
        $request = Request::instance();
        $data=$request->post();
        $fid=14;$fkid=$data["fkid"];
        $res=$this->goworker($fid,$fkid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
        if($res["operateStatus"]=="success"){
            try{
                Db::table("ap_fankui")->where(["id"=>$fkid])->update(["state"=>8]);
                Db::table("ap_apply_detail")->where(["fankui_id"=>$fkid])->update(["fankui_id"=>0,"fankuixiaoliang"=>0,"fankuiremark"=>null]);
            }catch (\Exception $e){
        
                          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                        }
                      return json_encode(["msg"=>"","state"=>1]);
            
        }else{
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
    }
    public function fktijiao($id){
        $jieguo=$this->gowork(14,$id);
                if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                    try{
                        Db::table("ap_fankui")->where(["id"=>$id])->update(["state"=>3]);
                    }catch (\Exception $e){
                    //return $e->getMessage();
                       
                        return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                    }
                    return $jieguo;
                }else{
                   
                    return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
    }
    //核销列表
    public function apCVcation($page=1,$list=10){
    	//获取类型列表
    	$states=Db::table("ti_state")->order("paixu")->select();
    	$this->assign("states",$states);
    	$request = Request::instance();

    	
    	$data=$request->post();
        $eid=Session::get("login_id");
    	$where="ap.is_deleted=0 and  ahp.is_deleted=0 and ahp.c_user_id=$eid ";
    	if($data){
    		if($data["no"])
    			$where.="and ahp.no={$data["no"]} ";
    		if(trim($data["title"]))
    			$where.="and ap.title like '%{$data["title"]}%' ";
    		if($data["state"])
    			$where.="and ahp.state={$data["state"]} ";
    		if(trim($data["start"]))
    			$where.="and ahp.created_on>='{$data["start"]} 00:00:00' ";
    		if(trim($data["end"]))
    			$where.="and ahp.created_on<='{$data["end"]} 23:59:59' ";
    	}else{
    		$data=["no"=>"","title"=>"","state"=>"","start"=>"","end"=>""];
    	}
//$this->assign("data",$data);
    $sum=Db::table("ap_hexiao_apply")->alias("ahp")
    ->join("ap_apply ap","ahp.apply_id=ap.id")
    ->join("ap_hexiao_detail ahd","ahp.id=ahd.hexiao_id")
    ->join("ti_state t","ahp.state=t.id")
    ->join("users uc","ahp.c_user_id=uc.id","LEFT")
    ->join("employee ec","uc.employee_id=ec.id","LEFT")
    ->where($where)
    ->group("ahp.id")->count();
    $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
	$applyde=Db::table("ap_hexiao_apply")->alias("ahp")
	->join("ap_apply ap","ahp.apply_id=ap.id")
	->join("ap_hexiao_detail ahd","ahp.id=ahd.hexiao_id")
	->join("ti_state t","ahp.state=t.id")
	->join("users uc","ahp.c_user_id=uc.id","LEFT")
    ->join("employee ec","uc.employee_id=ec.id","LEFT")
	->where($where)
	->group("ahp.id")->order("ahp.id desc")->limit($start,$list)
	->field("ahp.id,ahp.no,ap.title,sum(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as hanshui,ahp.is_fukuan,ahp.zfjine as zhifu,t.title as state_name,ec.em_name as cname,ahp.created_on,ahp.state as state,ap.id as apid")
	->select();
    for($i=0;$i<count($applyde);$i++){
         
            $applyde[$i]["myId"]=Db::table("cg_workflow")->where(["yw_id"=>$applyde[$i]["id"],"ywlx"=>15])->value("id");
        }
	$this->assign("applyde",$applyde);
    $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);
        $this->assign("data",$data);
    	return $this->fetch();
    }
    //新增核销
    public function apCostVerQuery(){

    	return $this->fetch();

    }
    //AP费用反馈详情
    public function apfkshenhe($myId,$trackId,$workId){
        $workfloawde=Db::table("cg_workflow")->where(["id"=>$myId])->find();
        $fkid=$workfloawde["yw_id"];
        $tmp=Db::table("ap_apply_detail")->where(["fankui_id"=>$fkid])->find();
        $aid=$tmp["apply_id"];
        $this->assign("fkid",$fkid);$this->assign("aid",$aid);
        $vo=Db::table("ap_fankui")->where(["id"=>$fkid])->find();
        if($vo["state"]==2){
            $this->redirect('Apapply/fkup', ['aid' => $aid,"fkid"=>$fkid,"from"=>2]);
        }else{
             $apply=Db::table("ap_apply")->where(["id"=>$aid])->find();

        $this->assign("apply",$apply);

        $fk=Db::table("ap_fankui")->alias("fk")
        ->join("ti_state s","fk.state=s.id")
        ->join("users uc","fk.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
        ->where(["fk.id"=>$fkid,"de.index"=>1])
        ->field("fk.id,fk.no,ec.em_name as cname,d.de_name,fk.remark,fk.state,fk.is_shengxiao,fk.fujian")
        ->find();
        $this->assign("fk",$fk);
         $fujian=[];
            //print_r($apply);
            if($fk["fujian"]){
                $fujian=Db::table("annex")->where("id in ({$fk["fujian"]})")->select();
                //print_r($fujian);
            }
            $this->assign("fujian",$fujian);
        $fkde=Db::table("ap_apply_detail")->alias("apd")
        ->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
        ->join("cg_market_provice p","apd.sheng=p.id","LEFT")
        ->join("cg_market_city c","apd.shi=c.id","LEFT")
        ->join("cg_jxs j","apd.jxs=j.id","LEFT")
        ->join("cg_system s","apd.system=s.id","LEFT")
        ->join("cg_net n","apd.net=n.id","LEFT")
        ->join("pro_brands pb","apd.brand=pb.id","LEFT")
        ->join("pro_category pc","apd.category=pc.id","LEFT")
        ->join("pro_series ps","apd.series=ps.id","LEFT")
        ->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
        ->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
        ->join("gys g","apd.gys=g.id")
        ->join("cg_paymethod cp","apd.zfid=cp.id")
        ->where("apd.is_actived=1 and apd.is_deleted=0 and apd.fankui_id=$fkid and apd.isok=1")
        ->field("apd.id,apd.detail_no,g.no as gys_no,g.gys_name,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,apd.start_time,apd.end_time,k3.title as kemu3,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,zong_xiaoliang,apd.fankuixiaoliang")
        ->select();
        //echo Db::table("ap_apply_detail")->getLastSql();
        //print_r($fkde);
        for($i=0;$i<count($fkde);$i++){
            $fkde[$i]["yujifeiyonglv"]=$fkde[$i]["hanshui"]/$fkde[$i]["zong_xiaoliang"]*100;
           $fkde[$i]["shijifeiyonglv"]=$fkde[$i]["hanshui"]/$fkde[$i]["fankuixiaoliang"]*100; 
        }
        $this->assign("fkde",$fkde);

        $all=Db::table("ap_apply_detail")->alias("apd")
        ->where("apd.is_actived=1 and apd.is_deleted=0 and apd.fankui_id=$fkid")
        ->group("apd.fankui_id")
        ->field("sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,sum(zong_xiaoliang) as zong_xiaoliang,sum(fankuixiaoliang) as fankuixiaoliang,sum(pifuzonge) as pifuzonges")
        ->find();
        $this->assign("all",$all);
        $feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge,sum(apd.zong_xiaoliang) as xiaoliangs from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid  group by k3.id,k3.title");
        $this->assign("feiyongs",$feiyongs);
        $contfeiyong=count($feiyongs);
        $this->assign("contfeiyong",$contfeiyong);
          $logs=$this->getlog(14,$fkid);
        //print_r($logs);
        $this->assign("logs",$logs);
        return $this->fetch();
        }

       
    }
    //AP费用反馈详情
    public function apFeedDetail($fkid,$aid){
    	$this->assign("fkid",$fkid);$this->assign("aid",$aid);
    	$apply=Db::table("ap_apply")->where(["id"=>$aid])->find();

    	$this->assign("apply",$apply);

    	$fk=Db::table("ap_fankui")->alias("fk")
    	->join("ti_state s","fk.state=s.id")
    	->join("users uc","fk.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
    	->where(["fk.id"=>$fkid,"de.index"=>1])
    	->field("fk.id,fk.no,ec.em_name as cname,d.de_name,fk.remark,fk.state,fk.is_shengxiao,fk.fujian")
    	->find();
    	$this->assign("fk",$fk);
        $fujian=[];
            //print_r($apply);
            if($fk["fujian"]){
                $fujian=Db::table("annex")->where("id in ({$fk["fujian"]})")->select();
                //print_r($fujian);
            }
        $this->assign("fujian",$fujian);
    	$fkde=Db::table("ap_apply_detail")->alias("apd")
    	->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    	->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    	->join("cg_market_city c","apd.shi=c.id","LEFT")
    	->join("cg_jxs j","apd.jxs=j.id","LEFT")
    	->join("cg_system s","apd.system=s.id","LEFT")
    	->join("cg_net n","apd.net=n.id","LEFT")
    	->join("pro_brands pb","apd.brand=pb.id","LEFT")
    	->join("pro_category pc","apd.category=pc.id","LEFT")
    	->join("pro_series ps","apd.series=ps.id","LEFT")
    	->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    	->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    	->join("gys g","apd.gys=g.id")
    	->join("cg_paymethod cp","apd.zfid=cp.id")
    	->where("apd.is_actived=1 and apd.is_deleted=0 and apd.fankui_id=$fkid and apd.isok=1")
    	->field("apd.id,apd.detail_no,g.no as gys_no,g.gys_name,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,apd.start_time,apd.end_time,k3.title as kemu3,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,zong_xiaoliang,apd.fankuixiaoliang")
    	->select();
    	//echo Db::table("ap_apply_detail")->getLastSql();
    	//print_r($fkde);
        for($i=0;$i<count($fkde);$i++){
            $fkde[$i]["yujifeiyonglv"]=$fkde[$i]["hanshui"]/$fkde[$i]["zong_xiaoliang"]*100;
           $fkde[$i]["shijifeiyonglv"]=$fkde[$i]["hanshui"]/$fkde[$i]["fankuixiaoliang"]*100; 
        }
    	$this->assign("fkde",$fkde);

    	$all=Db::table("ap_apply_detail")->alias("apd")
    	->where("apd.is_actived=1 and apd.is_deleted=0 and apd.fankui_id=$fkid")
    	->group("apd.fankui_id")
    	->field("sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,sum(zong_xiaoliang) as zong_xiaoliang,sum(fankuixiaoliang) as fankuixiaoliang,sum(pifuzonge) as pifuzonges")
    	->find();
    	$this->assign("all",$all);
    	$feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge,sum(apd.zong_xiaoliang) as xiaoliangs from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid  group by k3.id,k3.title");
    	$this->assign("feiyongs",$feiyongs);
    	$contfeiyong=count($feiyongs);
    	$this->assign("contfeiyong",$contfeiyong);
          $logs=$this->getlog(14,$fkid);
        //print_r($logs);
        $this->assign("logs",$logs);
    	return $this->fetch();
    }
    //导出反馈
    public function daochufankui($aid,$fkid){
    	$apply=Db::table("ap_apply")->where(["id"=>$aid])->find();

    	$this->assign("apply",$apply);

    	$fk=Db::table("ap_fankui")->alias("fk")
    	->join("ti_state s","fk.state=s.id")
    	->join("users uc","fk.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
    	->where(["fk.id"=>$fkid,"de.index"=>1])
    	->field("fk.id,fk.no,ec.em_name as cname,d.de_name,fk.remark,fk.state,fk.is_shengxiao,fk.created_on")
    	->find();
    

    	$fkde=Db::table("ap_apply_detail")->alias("apd")
    	->join("cg_market_zoning z","apd.fenqu=z.id","LEFT")
    	->join("cg_market_provice p","apd.sheng=p.id","LEFT")
    	->join("cg_market_city c","apd.shi=c.id","LEFT")
    	->join("cg_jxs j","apd.jxs=j.id","LEFT")
    	->join("cg_system s","apd.system=s.id","LEFT")
    	->join("cg_net n","apd.net=n.id","LEFT")
    	->join("pro_brands pb","apd.brand=pb.id","LEFT")
    	->join("pro_category pc","apd.category=pc.id","LEFT")
    	->join("pro_series ps","apd.series=ps.id","LEFT")
    	->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    	->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    	->join("gys g","apd.gys=g.id")
    	->join("cg_paymethod cp","apd.zfid=cp.id")
    	->where("apd.is_actived=1 and apd.is_deleted=0 and apd.fankui_id=$fkid")
    	->field("apd.id,apd.detail_no,g.no as gys_no,g.gys_name,n.title as net,pb.brand_name as brand,pc.category_name as category,ps.series_name as series,apd.start_time,apd.end_time,k3.title as kemu3,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,zong_xiaoliang,apd.fankuixiaoliang,description")
    	->select();
    	//echo Db::table("ap_apply_detail")->getLastSql();
    	//print_r($fkde);
    	

    	$all=Db::table("ap_apply_detail")->alias("apd")
    	->where("apd.is_actived=1 and apd.is_deleted=0 and apd.fankui_id=$fkid")
    	->group("apd.fankui_id")
    	->field("sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,sum(zong_xiaoliang) as zong_xiaoliang,sum(fankuixiaoliang) as fankuixiaoliang,sum(pifuzonge) as pifuzonges")
    	->find();
    	
    	$feiyongs=Db::table("ap_apply_detail")->query("select k3.title,sum(apd.pifuzonge) as kezonge,sum(apd.zong_xiaoliang) as xiaoliangs from ap_apply_detail as apd inner join cg_feiyongkemu3 as k3 on apd.feiyong_id=k3.id where apd.apply_id=$aid  group by k3.id,k3.title");
    	
    	$contfeiyong=count($feiyongs);

    		$eid=Session::get("employee_id");
    		$users=Db::table("employee")->where(["id"=>$eid])->find();

	  Vendor("PHPExcel");
        
        
    	  Vendor("PHPExcel.Writer.Excel5");

       // Loader::import('PHPExcel.Classes.PHPExcel');
        //Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
       //  Vendor("Excel.PHPExcel.Writer.Excel2007");
        $objPHPExcel= new PHPExcel();
            
            
        $objProps=$objPHPExcel->getProperties();
            
        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");
            	
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("AP费用反馈申请完整版");



         #标题
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('3')->setRowHeight(20);

        $objPHPExcel->getActiveSheet()->mergeCells('A1:Q1');
        $objPHPExcel->getActiveSheet()->setCellValue('A1',$apply["title"]."  费用反馈申请单");
              //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(14);

            #################表头信息
        $objPHPExcel->getActiveSheet()->mergeCells('A2:Q2');
        $objPHPExcel->getActiveSheet()->setCellValue('A2',"(本表单由软件导出，导出时间：".date("Y-m-d H:i:s")."；导出人：{$users["em_name"]})");
                //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);

         #################申请标题
        $objPHPExcel->getActiveSheet()->mergeCells('A3:Q3');
        $objPHPExcel->getActiveSheet()->setCellValue('A3',$apply["title"]);
      	//垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setSize(11);

         #单据信息
         $objPHPExcel->getActiveSheet()->setCellValue('A4',"编号");
         $objPHPExcel->getActiveSheet()->setCellValueExplicit('B4',$fk["no"],PHPExcel_Cell_DataType::TYPE_STRING);
         $objPHPExcel->getActiveSheet()->setCellValue('C4',"原申请编号");
         $objPHPExcel->getActiveSheet()->setCellValueExplicit('D4',$apply["no"],PHPExcel_Cell_DataType::TYPE_STRING);
         $objPHPExcel->getActiveSheet()->setCellValue('E4',"类型");
         $objPHPExcel->getActiveSheet()->setCellValue('F4',"AP费用");
         $objPHPExcel->getActiveSheet()->setCellValue('G4',"反馈时间");
         $objPHPExcel->getActiveSheet()->setCellValueExplicit('H4',$fk["created_on"],PHPExcel_Cell_DataType::TYPE_STRING);
          $objPHPExcel->getActiveSheet()->setCellValue('I4',"反馈人");
         $objPHPExcel->getActiveSheet()->setCellValue('J4',$fk["cname"]);
          $objPHPExcel->getActiveSheet()->setCellValue('K4',"所属部门");
         $objPHPExcel->getActiveSheet()->setCellValue('L4',$fk["de_name"]);
          $objPHPExcel->getActiveSheet()->setCellValue('M4',"备注");
         $objPHPExcel->getActiveSheet()->setCellValue('N4',$fk["remark"]);
         $objPHPExcel->getActiveSheet()->mergeCells('N4:Q4');

            $objPHPExcel->getActiveSheet()->getStyle('4')->getAlignment()->setWrapText(true);
           //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('4')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('4')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

           //填充背景色
        $objPHPExcel->getActiveSheet()->getStyle('A4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('C4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('C4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('E4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('E4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('G4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('G4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('I4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('I4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('K4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('K4')->getFill()->getStartColor()->setARGB('0099CCFF');
        
         #标题
        $objPHPExcel->getActiveSheet()->getStyle('6')->getAlignment()->setWrapText(true);
       	$objPHPExcel->getActiveSheet()->getRowDimension('6')->setRowHeight(40);
       
       	 $objPHPExcel->getActiveSheet()->getStyle('A6:Q6')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A6:Q6')->getFill()->getStartColor()->setARGB('0099CCFF');
        
         //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('6')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('6')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        $objPHPExcel->getActiveSheet()->setCellValue('A6',"状态");
        $objPHPExcel->getActiveSheet()->setCellValue('B6',"序号");
        $objPHPExcel->getActiveSheet()->setCellValue('C6',"原明细编号");
        $objPHPExcel->getActiveSheet()->setCellValue('D6',"供应商编号");
        $objPHPExcel->getActiveSheet()->setCellValue('E6',"供应商名称");
        $objPHPExcel->getActiveSheet()->setCellValue('F6',"网点名称");
        $objPHPExcel->getActiveSheet()->setCellValue('G6',"品牌");
        $objPHPExcel->getActiveSheet()->setCellValue('H6',"品类");
        $objPHPExcel->getActiveSheet()->setCellValue('I6',"系列");
        $objPHPExcel->getActiveSheet()->setCellValue('J6',"活动执行时间");
        $objPHPExcel->getActiveSheet()->setCellValue('K6',"三级费用科目");
        $objPHPExcel->getActiveSheet()->setCellValue('L6',"实际投入费用(元)");
        $objPHPExcel->getActiveSheet()->setCellValue('M6',"预计销量(元)");
        $objPHPExcel->getActiveSheet()->setCellValue('N6',"预计费用率");
        $objPHPExcel->getActiveSheet()->setCellValue('O6',"实际销量(元)");
        $objPHPExcel->getActiveSheet()->setCellValue('P6',"实际费用率");
        $objPHPExcel->getActiveSheet()->setCellValue('Q6',"活动描述");
        
        $h=6;
        for($i=0;$i<count($fkde);$i++){
        	$h++;$vo=$fkde[$i];
        	$objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setWrapText(true);
        	  //水平剧中
	        $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
	        //垂直剧中
	        $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        	 $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"正常");
        	 $objPHPExcel->getActiveSheet()->setCellValue('B'.$h,$i+1);
        	 $objPHPExcel->getActiveSheet()->setCellValue('C'.$h,$apply["no"].'_'.$vo["detail_no"]);
        	 $objPHPExcel->getActiveSheet()->setCellValue('D'.$h,$vo["gys_no"]);
        	 $objPHPExcel->getActiveSheet()->setCellValue('E'.$h,$vo["gys_name"]);
        	 $objPHPExcel->getActiveSheet()->setCellValue('F'.$h,$vo["net"]);
        	 $objPHPExcel->getActiveSheet()->setCellValue('G'.$h,$vo["brand"]);
        	 $objPHPExcel->getActiveSheet()->setCellValue('H'.$h,$vo["category"]);
        	 $objPHPExcel->getActiveSheet()->setCellValue('I'.$h,$vo["series"]);
        	 $objPHPExcel->getActiveSheet()->setCellValue('J'.$h,"从{$vo["start_time"]}至{$vo["end_time"]}");
        	 $objPHPExcel->getActiveSheet()->setCellValue('K'.$h,$vo["kemu3"]);
        	 $objPHPExcel->getActiveSheet()->setCellValueExplicit('L'.$h,round($vo["hanshui"],2),PHPExcel_Cell_DataType::TYPE_STRING);
        	 $objPHPExcel->getActiveSheet()->setCellValueExplicit('M'.$h,round($vo["zong_xiaoliang"],2),PHPExcel_Cell_DataType::TYPE_STRING);
             $yujifeiyonglv=round($vo["hanshui"]/$vo["zong_xiaoliang"]*100,2);
             $objPHPExcel->getActiveSheet()->setCellValueExplicit('N'.$h,$yujifeiyonglv.'%',PHPExcel_Cell_DataType::TYPE_STRING);
        	 $objPHPExcel->getActiveSheet()->setCellValueExplicit('O'.$h,round($vo["fankuixiaoliang"],2),PHPExcel_Cell_DataType::TYPE_STRING);
             $shijifeiyonglv=round($vo["hanshui"]/$vo["fankuixiaoliang"]*100,2);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('P'.$h,$shijifeiyonglv.'%',PHPExcel_Cell_DataType::TYPE_STRING);
        	 $objPHPExcel->getActiveSheet()->setCellValue('Q'.$h,$vo["description"]);
        }
        $h+=2;
         #归纳
	     $str="本申请中包含{$contfeiyong}个三级费用科目  其中";
	     for($i=0;$i<count($feiyongs);$i++){
	     	$str.="{$feiyongs[$i]["title"]}:".round($feiyongs[$i]["kezonge"],2)."(元)  ";
	     }
	     $str.="总预计未税费用:".round($all["pifuzonges"],2)."  （元）      总预计销售量：".round($all["zong_xiaoliang"],2)."（元） 总反馈销量 ".round($all["fankuixiaoliang"],2)."（元）";
	     $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,$str);
        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:Q{$h}");
        $h+=2;
			 $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"审批意见");
        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:Q{$h}");
         $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->getStartColor()->setARGB('0099CCFF');
        $logs=$this->getlog(14,$fkid);
         for($i=0;$i<count($logs);$i++){
            $h++;
            if($logs[$i]["COMMENTS"])
                $str="{$logs[$i]["USERNAME"]} 审批动作：{$logs[$i]["MEMO"]}；审批意见：{$logs[$i]["COMMENTS"]}(审批时间：{$logs[$i]["ACTIONTIME"]})";
            else
                $str="{$logs[$i]["USERNAME"]} 审批动作：{$logs[$i]["MEMO"]}；审批意见：无 (审批时间：{$logs[$i]["ACTIONTIME"]})";
             $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,$str);
            $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:Q{$h}");
        }
             $styleArray = array(  
        'borders' => array(  
            'allborders' => array(  
                //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框  
                //'color' => array('argb' => 'FFFF0000'),  
            ),  
        ),  
    );  
   $objPHPExcel->getActiveSheet()->getStyle('A1:Q'.$h)->applyFromArray($styleArray);//这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪


         $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
 		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(60);

    	$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
           ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=AP费用反馈申请表完整版.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        
        $objWriter->save('php://output');
    }
    public function hxtijiao($id){
        $jieguo=$this->gowork(15,$id);
                if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                    Db::commit();
                    return $jieguo;
                }else{
                    Db::rollBack();
                    return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
    }
    public function hxbaocunchuli(){
        $request = Request::instance();$data = $request->post();
       // print_r($data);exit;
        for($i=0;$i<count($data["yuan_hexiao"]);$i++){
            if(!$data["hexiao_weishui"]){
                return json_encode(["msg"=>"未税核销金额必须填写","state"=>2]);
            }
        }
        Db::startTrans();
        try{

            for($i=0;$i<count($data["yuan_hexiao"]);$i++){
                $up["id"]=$data["did"][$i];
                $up["hexiao_weishui"]=$data["hexiao_weishui"][$i];
                $up["hexiao_shuilv"]=$data["hexiao_shuilv"][$i];
                $up["has_fp"]=$data["isfa"][$i];
                $up["fp_no"]=$data["fp_no"][$i];
                $up["dikou"]=$data["isdi"][$i];
                $up["zfid"]=$data["zfid"][$i];
                DB::table("ap_hexiao_detail")->update($up);
              // print_r($up);exit;
                $detail=Db::table("ap_apply_detail")->where(["id"=>$data["detail_id"][$i]])->find();
               // print_r($detail);exit;
                $now=$detail["hexiao"]+$data["hexiao_weishui"][$i]-$data["yuan_hexiao"][$i];
                Db::table("ap_apply_detail")->where(["id"=>$data["detail_id"][$i]])->update(["hexiao"=>$now]);
            }
            Db::Table("ap_hexiao_apply")->where(["id"=>$data["hid"]])->update(["fujian"=>$data["attach"],"remark"=>$data["remark"],"state"=>3]);
        }catch (\Exception $e){
            Db::rollBack();
            return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
        }
        $res=$this->goworker(15,$data["hid"],$data["nodeKey"],$data["selectId"],$data["selectName"]);
        if($res["operateStatus"]=="success"){
            Db::commit();
            return json_encode(['state'=>1,'msg'=>'提交成功']);
        }else{
             Db::rollBack();
            return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
        }
    }
    public function hxxiugaichuli(){
        $request = Request::instance();$data = $request->post();
       // print_r($data);exit;
        for($i=0;$i<count($data["yuan_hexiao"]);$i++){
            if(!$data["hexiao_weishui"]){
                return json_encode(["msg"=>"未税核销金额必须填写","state"=>2]);
            }
        }
        Db::startTrans();
        try{

            for($i=0;$i<count($data["yuan_hexiao"]);$i++){
                $up["id"]=$data["did"][$i];
                $up["hexiao_weishui"]=$data["hexiao_weishui"][$i];
                $up["hexiao_shuilv"]=$data["hexiao_shuilv"][$i];
                $up["has_fp"]=$data["isfa"][$i];
                $up["fp_no"]=$data["fp_no"][$i];
                $up["dikou"]=$data["isdi"][$i];
                $up["zfid"]=$data["zfid"][$i];
                DB::table("ap_hexiao_detail")->update($up);
              // print_r($up);exit;
                $detail=Db::table("ap_apply_detail")->where(["id"=>$data["detail_id"][$i]])->find();
               // print_r($detail);exit;
                $now=$detail["hexiao"]+$data["hexiao_weishui"][$i]-$data["yuan_hexiao"][$i];
                Db::table("ap_apply_detail")->where(["id"=>$data["detail_id"][$i]])->update(["hexiao"=>$now]);
            }
            Db::Table("ap_hexiao_apply")->where(["id"=>$data["hid"]])->update(["fujian"=>$data["attach"],"remark"=>$data["remark"]]);
        }catch (\Exception $e){
            Db::rollBack();
            return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
        }
        if($data["state"]==3){
             $jieguo=$this->gowork(15,$data["hid"]);
                if($jieguo==json_encode(['state'=>1,'msg'=>'提交成功'])){
                    Db::commit();
                    return $jieguo;
                }else{
                    Db::rollBack();
                    return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
        }else{
            Db::commit();
             return json_encode(["msg"=>"","state"=>1]);
        }
    }
    public function hxxiugai($hid,$from=1){
        $this->assign("from",$from);
        $this->assign("hid",$hid);
        $apply=Db::table("ap_hexiao_apply")->alias("hd")
        ->join("ti_state s","hd.state=s.id")
        ->join("users uc","hd.c_user_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
        ->where(["hd.id"=>$hid,"de.index"=>1])
        ->field("hd.id,ec.em_name as cname,d.de_name,j.job_name,hd.no,hd.created_on,hd.remark,hd.is_shengxiao,hd.fujian,hd.state,hd.apply_id")
        ->find();
        $this->assign("apply",$apply);
        $aid=$apply["apply_id"];
         $fujian=[];
            //print_r($apply);
            if($apply["fujian"]){
                $fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
                //print_r($fujian);
            }
        $this->assign("fujian",$fujian);
        $gys=Db::table("ap_hexiao_detail")->alias("ahd")
        ->join("ap_apply_detail apd","ahd.detail_id=apd.id")
        ->join("gys g","apd.gys=g.id")
        ->where("ahd.hexiao_id=$hid")
        ->field("distinct g.gys_name")
        ->select();
        $tmp=[];
        for($i=0;$i<count($gys);$i++){
            $tmp[$i]=$gys[$i]["gys_name"];
        }
        $gys_str=implode(',',$tmp);
        $this->assign("gys_str",$gys_str);
        $applyde=Db::table("ap_hexiao_detail")->alias("ahd")
        ->join("ap_apply_detail apd","ahd.detail_id=apd.id")
        ->join("ap_hexiao_apply ahp","ahd.hexiao_id=ahp.id")
        ->join("ap_apply ap","apd.apply_id=ap.id")
        ->join("gys g","apd.gys=g.id")
        ->join("pro_brands pb","apd.brand=pb.id","LEFT")
        ->join("pro_category pc","apd.category=pc.id","LEFT")
        ->join("pro_series ps","apd.series=ps.id","LEFT")
        ->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
        ->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
        ->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("cg_channel_types1 c1","ap.channel_id=c1.id")
        ->join("cg_paymethod cp","ahd.zfid=cp.id")
        ->join("cg_paymethod cp1","apd.zfid=cp1.id")
        ->where("ahd.hexiao_id=$hid and apd.is_actived=1 and apd.is_deleted=0")
        ->field("ap.no,apd.detail_no,ec.em_name as cname,ap.id as apid,ahd.he_detail_no,ahp.no as he_no,c1.title as channel,g.gys_name,pb.brand_name as brand,k3.title as kemu3,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,apd.hexiao,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100-apd.hexiao) as weihe,ahd.hexiao_weishui,ahd.has_fp,ahd.fp_no,ahd.dikou,ahd.hexiao_shuilv,(ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as shuijin,(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as he_hanshui,apd.start_time,ahd.zfid as bczffs,cp1.title as zffs,ahd.beizhu,ahd.detail_id,ahd.id as ahdid,apd.id as apdid ")
        ->select();
        for($i=0;$i<count($applyde);$i++){
            $applyde[$i]["max"]=$applyde[$i]["hexiao_weishui"]+$applyde[$i]["weihe"];
        }
        $this->assign("applyde",$applyde);

        $pay=Db::table("cg_paymethod")->select();
        $this->assign("pay",$pay);
        $all=Db::table("ap_hexiao_detail")->alias("ahd")
        ->join("ap_hexiao_apply ahp","ahd.hexiao_id=ahp.id")
        ->join("ap_apply_detail apd","ahd.detail_id=apd.id")
        ->where("ahd.hexiao_id=$hid and apd.is_actived=1 and apd.is_deleted=0")
        ->field("sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,sum(hexiao) as hexiao,sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100-apd.hexiao) as weihe,sum(hexiao_weishui) as hexiao_weishui,sum(ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as shuijin,sum(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as he_hanshui,ahp.zfjine as zhifu_jine,sum(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100)-ahp.zfjine as weifu")
        ->find();
        $this->assign("all",$all);
        //支付详细
        $zhifus=Db::table("ap_zhifu")->alias("az")
        ->join("employee ec","az.z_users_id=ec.id","LEFT")
        ->where(["az.is_deleted"=>0,"az.is_actived"=>1,"az.hexiao_id"=>$hid])
        ->field("az.zfpz,ec.em_name as cname,az.zhifu_day,az.zfjin,az.remark")
        ->select();

        $this->assign("zhifus",$zhifus);
         $logs=$this->getlog(15,$hid);
        //print_r($logs);
        $this->assign("logs",$logs);
        $btn=$this->getbton(15,$hid);
        $this->assign("btn",$btn);
        return $this->fetch();
    }
    //ap核销明细
    public function apCostVerifyDetail($hid,$aid){
    	$this->assign("hid",$hid);
    	$apply=Db::table("ap_hexiao_apply")->alias("hd")
    	->join("ti_state s","hd.state=s.id")
    	->join("users uc","hd.c_user_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
    	->where(["hd.id"=>$hid,"de.index"=>1])
    	->field("hd.id,ec.em_name as cname,d.de_name,j.job_name,hd.no,hd.created_on,hd.remark,hd.is_shengxiao,hd.fujian,hd.state")
    	->find();
    	$this->assign("apply",$apply);
            $fujian=[];
            //print_r($apply);
            if($apply["fujian"]){
                $fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
                //print_r($fujian);
            }
        $this->assign("fujian",$fujian);
    	$gys=Db::table("ap_hexiao_detail")->alias("ahd")
    	->join("ap_apply_detail apd","ahd.detail_id=apd.id")
    	->join("gys g","apd.gys=g.id")
    	->where("ahd.hexiao_id=$hid")
    	->field("distinct g.gys_name")
    	->select();
    	$tmp=[];
    	for($i=0;$i<count($gys);$i++){
    		$tmp[$i]=$gys[$i]["gys_name"];
    	}
    	$gys_str=implode(',',$tmp);
    	$this->assign("gys_str",$gys_str);
    	$applyde=Db::table("ap_hexiao_detail")->alias("ahd")
    	->join("ap_apply_detail apd","ahd.detail_id=apd.id")
    	->join("ap_hexiao_apply ahp","ahd.hexiao_id=ahp.id")
    	->join("ap_apply ap","apd.apply_id=ap.id")
    	->join("gys g","apd.gys=g.id")
    	->join("pro_brands pb","apd.brand=pb.id","LEFT")
    	->join("pro_category pc","apd.category=pc.id","LEFT")
    	->join("pro_series ps","apd.series=ps.id","LEFT")
    	->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    	->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    	->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("cg_channel_types1 c1","ap.channel_id=c1.id")
        ->join("cg_paymethod cp","ahd.zfid=cp.id")
        ->join("cg_paymethod cp1","apd.zfid=cp1.id")
    	->where("ahd.hexiao_id=$hid and apd.is_actived=1 and apd.is_deleted=0")
    	->field("ap.no,apd.detail_no,ec.em_name as cname,ap.id as apid,ahd.he_detail_no,ahp.no as he_no,c1.title as channel,g.gys_name,pb.brand_name as brand,k3.title as kemu3,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,apd.hexiao,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100-apd.hexiao) as weihe,ahd.hexiao_weishui,ahd.has_fp,ahd.fp_no,ahd.dikou,ahd.hexiao_shuilv,(ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as shuijin,(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as he_hanshui,apd.start_time,cp.title as bczffs,cp1.title as zffs,ahd.beizhu,apd.id as apdid ")
    	->select();
    	$this->assign("applyde",$applyde);

    	$all=Db::table("ap_hexiao_detail")->alias("ahd")
    	->join("ap_hexiao_apply ahp","ahd.hexiao_id=ahp.id")
    	->join("ap_apply_detail apd","ahd.detail_id=apd.id")
    	->where("ahd.hexiao_id=$hid and apd.is_actived=1 and apd.is_deleted=0")
    	->field("sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,sum(hexiao) as hexiao,sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100-apd.hexiao) as weihe,sum(hexiao_weishui) as hexiao_weishui,sum(ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as shuijin,sum(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as he_hanshui,ahp.zfjine as zhifu_jine,sum(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100)-ahp.zfjine as weifu")
    	->find();
    	$this->assign("all",$all);
    	//支付详细
    	$zhifus=Db::table("ap_zhifu")->alias("az")
        ->join("employee ec","az.z_users_id=ec.id","LEFT")
        ->where(["az.is_deleted"=>0,"az.is_actived"=>1,"az.hexiao_id"=>$hid])
        ->field("az.zfpz,ec.em_name as cname,az.zhifu_day,az.zfjin,az.remark")
        ->select();
        $this->assign("zhifus",$zhifus);
         $logs=$this->getlog(15,$hid);
        //print_r($logs);
        $this->assign("logs",$logs);
    	return $this->fetch();
    }
    public function hxzuofeichuli(){
        $request = Request::instance();$data = $request->post();
        //print_r($data);exit;
        $fid=15;$aid=$data["hid"];
        $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
        if($res["operateStatus"]=="success"){
            try{
                 $arr=Db::table("ap_hexiao_detail")->where(["hexiao_id"=>$aid])->select();
                for($i=0;$i<count($arr);$i++){
                    $tmp=Db::table("ap_apply_detail")->where(["id"=>$arr[$i]["detail_id"]])->find();
                    $upde["id"]=$arr[$i]["detail_id"];
                    $upde["hexiao"]=$tmp["hexiao"]-$arr[$i]["hexiao_weishui"];
                    if($arr[$i]["buyu_he"])
                        $upde["buyu_he"]=0;
                    Db::table("ap_apply_detail")->update($upde);
                }
                Db::table("ap_hexiao_apply")->where(["id"=>$aid])->update(["state"=>8]);
            }catch (\Exception $e){
        
                          return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                        }
                      return json_encode(["msg"=>"","state"=>1]);
            
        }else{
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
    }
    //ap核销明细
    public function aphxshenhe($myId,$trackId,$workId){
        $workfloawde=Db::table("cg_workflow")->where(["id"=>$myId])->find();
        $hid=$workfloawde["yw_id"];
        $this->assign("hid",$hid);
        $aid=Db::table("ap_hexiao_apply")->where(["id"=>$hid])->value("apply_id");
        $state=Db::table("ap_hexiao_apply")->where(["id"=>$hid])->value("state");
        if($state==2){
            $this->redirect('Apapply/hxxiugai', ['hid' => $hid,"from"=>2]);
        }else{
            $apply=Db::table("ap_hexiao_apply")->alias("hd")
            ->join("ti_state s","hd.state=s.id")
            ->join("users uc","hd.c_user_id=uc.id","LEFT")
            ->join("employee ec","uc.employee_id=ec.id","LEFT")
            ->join("job_employee je","ec.id=je.employee_id","LEFT")
            ->join("job j","je.job_id=j.id","LEFT")
            ->join("department_employee de","ec.id=de.employee_id","LEFT")
            ->join("department d","de.department_id=d.id","LEFT")
            ->where(["hd.id"=>$hid,"de.index"=>1])
            ->field("hd.id,ec.em_name as cname,d.de_name,j.job_name,hd.no,hd.created_on,hd.remark,hd.is_shengxiao,hd.fujian")
            ->find();
            $this->assign("apply",$apply);
                $fujian=[];
                //print_r($apply);
                if($apply["fujian"]){
                    $fujian=Db::table("annex")->where("id in ({$apply["fujian"]})")->select();
                    //print_r($fujian);
                }
            $this->assign("fujian",$fujian);
            $gys=Db::table("ap_hexiao_detail")->alias("ahd")
            ->join("ap_apply_detail apd","ahd.detail_id=apd.id")
            ->join("gys g","apd.gys=g.id")
            ->where("ahd.hexiao_id=$hid")
            ->field("distinct g.gys_name")
            ->select();
            $tmp=[];
            for($i=0;$i<count($gys);$i++){
                $tmp[$i]=$gys[$i]["gys_name"];
            }
            $gys_str=implode(',',$tmp);
            $this->assign("gys_str",$gys_str);
            $applyde=Db::table("ap_hexiao_detail")->alias("ahd")
            ->join("ap_apply_detail apd","ahd.detail_id=apd.id")
            ->join("ap_hexiao_apply ahp","ahd.hexiao_id=ahp.id")
            ->join("ap_apply ap","apd.apply_id=ap.id")
            ->join("gys g","apd.gys=g.id")
            ->join("pro_brands pb","apd.brand=pb.id","LEFT")
            ->join("pro_category pc","apd.category=pc.id","LEFT")
            ->join("pro_series ps","apd.series=ps.id","LEFT")
            ->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
            ->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
            ->join("users uc","ap.c_users_id=uc.id","LEFT")
            ->join("employee ec","uc.employee_id=ec.id","LEFT")
            ->join("cg_channel_types1 c1","ap.channel_id=c1.id")
            ->join("cg_paymethod cp","ahd.zfid=cp.id")
            ->join("cg_paymethod cp1","apd.zfid=cp1.id")
            ->where("ahd.hexiao_id=$hid and apd.is_actived=1 and apd.is_deleted=0")
            ->field("ap.no,apd.detail_no,ec.em_name as cname,ap.id as apid,ahd.he_detail_no,ahp.no as he_no,c1.title as channel,g.gys_name,pb.brand_name as brand,k3.title as kemu3,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,apd.hexiao,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100-apd.hexiao) as weihe,ahd.hexiao_weishui,ahd.has_fp,ahd.fp_no,ahd.dikou,ahd.hexiao_shuilv,(ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as shuijin,(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as he_hanshui,apd.start_time,cp.title as bczffs,cp1.title as zffs,ahd.beizhu,apd.id as apdid ")
            ->select();
            $this->assign("applyde",$applyde);

            $all=Db::table("ap_hexiao_detail")->alias("ahd")
            ->join("ap_hexiao_apply ahp","ahd.hexiao_id=ahp.id")
            ->join("ap_apply_detail apd","ahd.detail_id=apd.id")
            ->where("ahd.hexiao_id=$hid and apd.is_actived=1 and apd.is_deleted=0")
            ->field("sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,sum(hexiao) as hexiao,sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100-apd.hexiao) as weihe,sum(hexiao_weishui) as hexiao_weishui,sum(ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as shuijin,sum(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as he_hanshui,ahp.zfjine as zhifu_jine,sum(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100)-ahp.zfjine as weifu")
            ->find();
            $this->assign("all",$all);
            //支付详细
            $zhifus=Db::table("ap_zhifu")->alias("az")
            ->join("employee ec","az.z_users_id=ec.id","LEFT")
            ->where(["az.is_deleted"=>0,"az.is_actived"=>1,"az.hexiao_id"=>$hid])
            ->field("az.zfpz,ec.em_name as cname,az.zhifu_day,az.zfjin,az.remark")
            ->select();
            $this->assign("zhifus",$zhifus);
             $logs=$this->getlog(15,$hid);
            //print_r($logs);
            $this->assign("logs",$logs);
            return $this->fetch();
        }
        
    }
    public function daochuhexiao($hid){

    	$apply=Db::table("ap_hexiao_apply")->alias("hd")
    	->join("ti_state s","hd.state=s.id")
    	->join("users uc","hd.c_user_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("job_employee je","ec.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->join("department_employee de","ec.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
    	->where(["hd.id"=>$hid,"de.index"=>1])
    	->field("hd.id,ec.em_name as cname,d.de_name,j.job_name,hd.no,hd.created_on,hd.remark,hd.is_shengxiao")
    	->find();
    	
    	$gys=Db::table("ap_hexiao_detail")->alias("ahd")
    	->join("ap_apply_detail apd","ahd.detail_id=apd.id")
    	->join("gys g","apd.gys=g.id")
    	->where("ahd.hexiao_id=$hid")
    	->field("distinct g.gys_name")
    	->select();
    	$tmp=[];
    	for($i=0;$i<count($gys);$i++){
    		$tmp[$i]=$gys[$i]["gys_name"];
    	}
    	$gys_str=implode(',',$tmp);
    	
    	$applyde=Db::table("ap_hexiao_detail")->alias("ahd")
    	->join("ap_apply_detail apd","ahd.detail_id=apd.id")
    	->join("ap_hexiao_apply ahp","ahd.hexiao_id=ahp.id")
    	->join("ap_apply ap","apd.apply_id=ap.id")
    	->join("gys g","apd.gys=g.id")
    	->join("pro_brands pb","apd.brand=pb.id","LEFT")
    	->join("pro_category pc","apd.category=pc.id","LEFT")
    	->join("pro_series ps","apd.series=ps.id","LEFT")
    	->join("cg_feiyongkemu3 k3","apd.feiyong_id=k3.id","LEFT")
    	->join("cg_feiyongkemu2 k2","k3.pid=k2.id","LEFT")
    	->join("users uc","ap.c_users_id=uc.id","LEFT")
        ->join("employee ec","uc.employee_id=ec.id","LEFT")
        ->join("cg_channel_types1 c1","ap.channel_id=c1.id")
        ->join("cg_paymethod cp","ahd.zfid=cp.id")
        ->join("cg_paymethod cp1","apd.zfid=cp1.id")
    	->where("ahd.hexiao_id=$hid and apd.is_actived=1 and apd.is_deleted=0")
    	->field("ap.no,apd.detail_no,ec.em_name as cname,ap.id as apid,ahd.he_detail_no,ahp.no as he_no,c1.title as channel,g.gys_name,pb.brand_name as brand,k3.title as kemu3,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,apd.hexiao,(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100-apd.hexiao) as weihe,ahd.hexiao_weishui,ahd.has_fp,ahd.fp_no,ahd.dikou,ahd.hexiao_shuilv,(ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as shuijin,(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as he_hanshui,apd.start_time,cp.title as bczffs,cp1.title as zffs,ahd.beizhu ")
    	->select();
    	

    	
    	$all=Db::table("ap_hexiao_detail")->alias("ahd")
    	->join("ap_hexiao_apply ahp","ahd.hexiao_id=ahp.id")
    	->join("ap_apply_detail apd","ahd.detail_id=apd.id")
    	->where("ahd.hexiao_id=$hid and apd.is_actived=1 and apd.is_deleted=0")
    	->field("sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100) as hanshui,sum(hexiao) as hexiao,sum(apd.pifuzonge+apd.pifuzonge*apd.shuilv/100-apd.hexiao) as weihe,sum(hexiao_weishui) as hexiao_weishui,sum(ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as shuijin,sum(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100) as he_hanshui,ahp.zfjine as zhifu_jine,sum(ahd.hexiao_weishui+ahd.hexiao_weishui*ahd.hexiao_shuilv/100)-ahp.zfjine as weifu")
    	->find();
    			$eid=Session::get("employee_id");
    		$users=Db::table("employee")->where(["id"=>$eid])->find();

	  Vendor("PHPExcel");
        
        
    	  Vendor("PHPExcel.Writer.Excel5");

       // Loader::import('PHPExcel.Classes.PHPExcel');
        //Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
       //  Vendor("Excel.PHPExcel.Writer.Excel2007");
        $objPHPExcel= new PHPExcel();
            
            
        $objProps=$objPHPExcel->getProperties();
            
        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");
            	
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("AP费用核销申请完整版");



         #标题
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('3')->setRowHeight(20);


          $objPHPExcel->getActiveSheet()->mergeCells('A1:Y1');
        $objPHPExcel->getActiveSheet()->setCellValue('A1', $gys_str."费用核销申请单");
              //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(14);

            #################表头信息
        $objPHPExcel->getActiveSheet()->mergeCells('A2:Y2');
        $objPHPExcel->getActiveSheet()->setCellValue('A2',"(本表单由软件导出，导出时间：".date("Y-m-d H:i:s")."；导出人：{$users["em_name"]})");
                //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);

         #################申请标题
        $objPHPExcel->getActiveSheet()->mergeCells('A3:Y3');
        $objPHPExcel->getActiveSheet()->setCellValue('A3',$gys_str."费用核销申请单");
      	//垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setSize(11);


          #单据信息
         $objPHPExcel->getActiveSheet()->setCellValue('A4',"编号");
         $objPHPExcel->getActiveSheet()->setCellValueExplicit('B4',$apply["no"],PHPExcel_Cell_DataType::TYPE_STRING);
         $objPHPExcel->getActiveSheet()->setCellValue('C4',"申请人");
         $objPHPExcel->getActiveSheet()->setCellValue('D4',$apply["cname"]);
         $objPHPExcel->getActiveSheet()->setCellValue('E4',"申请人所在部门");
         $objPHPExcel->getActiveSheet()->setCellValue('F4',$apply["de_name"]);
         $objPHPExcel->getActiveSheet()->setCellValue('G4',"职位");
         $objPHPExcel->getActiveSheet()->setCellValue('H4',$apply["job_name"]);
          $objPHPExcel->getActiveSheet()->setCellValue('I4',"提交时间");
         $objPHPExcel->getActiveSheet()->setCellValue('J4',$apply["created_on"]);
          $objPHPExcel->getActiveSheet()->setCellValue('K4',"供应商名称");
         $objPHPExcel->getActiveSheet()->setCellValue('L4',$gys_str);
          $objPHPExcel->getActiveSheet()->setCellValue('O4',"备注");
         $objPHPExcel->getActiveSheet()->setCellValue('P4',$apply["remark"]);
         $objPHPExcel->getActiveSheet()->mergeCells('L4:N4');
         $objPHPExcel->getActiveSheet()->mergeCells('P4:Y4');
            $objPHPExcel->getActiveSheet()->getStyle('4')->getAlignment()->setWrapText(true);
           //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('4')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('4')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

           //填充背景色
        $objPHPExcel->getActiveSheet()->getStyle('A4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('C4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('C4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('E4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('E4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('G4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('G4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('I4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('I4')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('K4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('K4')->getFill()->getStartColor()->setARGB('0099CCFF');
          $objPHPExcel->getActiveSheet()->getStyle('O4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('O4')->getFill()->getStartColor()->setARGB('0099CCFF');

         #标题
        $objPHPExcel->getActiveSheet()->getStyle('6')->getAlignment()->setWrapText(true);
       	$objPHPExcel->getActiveSheet()->getRowDimension('6')->setRowHeight(20);
       	$objPHPExcel->getActiveSheet()->getStyle('7')->getAlignment()->setWrapText(true);
       	$objPHPExcel->getActiveSheet()->getRowDimension('7')->setRowHeight(40);
       	 $objPHPExcel->getActiveSheet()->getStyle('A6:Y6')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A6:Y6')->getFill()->getStartColor()->setARGB('0099CCFF');
         $objPHPExcel->getActiveSheet()->getStyle('A7:Y7')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle('A7:Y7')->getFill()->getStartColor()->setARGB('0099CCFF');
         //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('6')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('6')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

 //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('7')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('7')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

         $objPHPExcel->getActiveSheet()->setCellValue('A6',"序号");
        $objPHPExcel->getActiveSheet()->mergeCells('A6:A7');
         $objPHPExcel->getActiveSheet()->setCellValue('B6',"明细编号");
        $objPHPExcel->getActiveSheet()->mergeCells('B6:B7');
        $objPHPExcel->getActiveSheet()->setCellValue('C6',"原申请人");
        $objPHPExcel->getActiveSheet()->mergeCells('C6:C7');
        $objPHPExcel->getActiveSheet()->setCellValue('D6',"原申请文件");
        $objPHPExcel->getActiveSheet()->mergeCells('D6:D7');
        $objPHPExcel->getActiveSheet()->setCellValue('E6',"原明细编号");
        $objPHPExcel->getActiveSheet()->mergeCells('E6:E7');
        $objPHPExcel->getActiveSheet()->setCellValue('F6',"渠道类型");
        $objPHPExcel->getActiveSheet()->mergeCells('F6:F7');
        $objPHPExcel->getActiveSheet()->setCellValue('G6',"供应商名称");
        $objPHPExcel->getActiveSheet()->mergeCells('G6:G7');
         $objPHPExcel->getActiveSheet()->setCellValue('H6',"品牌");
        $objPHPExcel->getActiveSheet()->mergeCells('H6:H7');
        $objPHPExcel->getActiveSheet()->setCellValue('I6',"三级费用科目");
        $objPHPExcel->getActiveSheet()->mergeCells('I6:I7');
        $objPHPExcel->getActiveSheet()->setCellValue('J6',"实际投入");
        $objPHPExcel->getActiveSheet()->mergeCells('J6:L6');
        $objPHPExcel->getActiveSheet()->setCellValue('J7',"实际投入金额");
        $objPHPExcel->getActiveSheet()->setCellValue('k7',"已核销金额");
        $objPHPExcel->getActiveSheet()->setCellValue('L7',"未核销金额");
         $objPHPExcel->getActiveSheet()->setCellValue('M6',"本次申请核销");
        $objPHPExcel->getActiveSheet()->mergeCells('M6:T6');
         $objPHPExcel->getActiveSheet()->setCellValue('M7',"未税核销金额");
         $objPHPExcel->getActiveSheet()->setCellValue('N7',"有无发票");
         $objPHPExcel->getActiveSheet()->setCellValue('O7',"发票号");
         $objPHPExcel->getActiveSheet()->setCellValue('P7',"是否增值税(可抵扣)");
         $objPHPExcel->getActiveSheet()->setCellValue('Q7',"税率");
         $objPHPExcel->getActiveSheet()->setCellValue('R7',"税金");
         $objPHPExcel->getActiveSheet()->setCellValue('S7',"含税核销金额");
         $objPHPExcel->getActiveSheet()->setCellValue('T7',"实际核销金额");

         $objPHPExcel->getActiveSheet()->setCellValue('U6',"活动开始日期");
        $objPHPExcel->getActiveSheet()->mergeCells('U6:U7');
 		$objPHPExcel->getActiveSheet()->setCellValue('V6',"支付方式");
        $objPHPExcel->getActiveSheet()->mergeCells('V6:V7');
         $objPHPExcel->getActiveSheet()->setCellValue('W6',"本次支付方式");
        $objPHPExcel->getActiveSheet()->mergeCells('W6:W7');
         $objPHPExcel->getActiveSheet()->setCellValue('X6',"备注");
        $objPHPExcel->getActiveSheet()->mergeCells('X6:X7');
         $objPHPExcel->getActiveSheet()->setCellValue('Y6',"操作");
        $objPHPExcel->getActiveSheet()->mergeCells('Y6:Y7');

        $h=7;
        for($i=0;$i<count($applyde);$i++){
        	$h++;$vo=$applyde[$i];
        	$objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setWrapText(true);
        	  //水平剧中
	        $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
	        //垂直剧中
	        $objPHPExcel->getActiveSheet()->getStyle($h)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        	$objPHPExcel->getActiveSheet()->setCellValue('A'.$h,$i);
        	$objPHPExcel->getActiveSheet()->setCellValue('B'.$h,"{$vo["he_no"]}_{$vo["he_detail_no"]}");
        	$objPHPExcel->getActiveSheet()->setCellValue('C'.$h,$vo["cname"]);
        	$objPHPExcel->getActiveSheet()->setCellValueExplicit('D'.$h,"{$vo["no"]}",PHPExcel_Cell_DataType::TYPE_STRING);
        	$objPHPExcel->getActiveSheet()->setCellValue('E'.$h,"{$vo["no"]}_{$vo["detail_no"]}");
        	$objPHPExcel->getActiveSheet()->setCellValue('F'.$h,$vo["channel"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('G'.$h,$vo["gys_name"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('H'.$h,$vo["brand"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('I'.$h,$vo["kemu3"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('J'.$h,round($vo["hanshui"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('K'.$h,round($vo["hexiao"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('L'.$h,round($vo["weihe"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('M'.$h,round($vo["hexiao_weishui"],2));
        	if($vo["has_fp"]){
        		$objPHPExcel->getActiveSheet()->setCellValue('N'.$h,"有");
        	}else{
        		$objPHPExcel->getActiveSheet()->setCellValue('N'.$h,"无");
        	}
        	$objPHPExcel->getActiveSheet()->setCellValue('O'.$h,$vo["fp_no"]);
        	if($vo["dikou"]){
        		$objPHPExcel->getActiveSheet()->setCellValue('P'.$h,"是");
        	}else{
        		$objPHPExcel->getActiveSheet()->setCellValue('P'.$h,"否");
        	}
        	$objPHPExcel->getActiveSheet()->setCellValue('Q'.$h,round($vo["hexiao_shuilv"],2)."%");
        	$objPHPExcel->getActiveSheet()->setCellValue('R'.$h,round($vo["shuijin"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('S'.$h,round($vo["he_hanshui"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('T'.$h,round($vo["he_hanshui"],2));
        	$objPHPExcel->getActiveSheet()->setCellValue('U'.$h,$vo["start_time"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('V'.$h,$vo["zffs"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('W'.$h,$vo["bczffs"]);
        	$objPHPExcel->getActiveSheet()->setCellValue('X'.$h,$vo["beizhu"]);
        }
        $h++;
        #合计
       	$objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"总计");
        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:I{$h}");
         //水平剧中
	        $objPHPExcel->getActiveSheet()->getStyle('A'.$h)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
		$objPHPExcel->getActiveSheet()->setCellValue('J'.$h,round($all["hanshui"],2));
		$objPHPExcel->getActiveSheet()->setCellValue('K'.$h,round($all["hexiao"],2));
		$objPHPExcel->getActiveSheet()->setCellValue('L'.$h,round($all["weihe"],2));
		$objPHPExcel->getActiveSheet()->setCellValue('M'.$h,round($all["hexiao_weishui"],2));
		$objPHPExcel->getActiveSheet()->setCellValue('R'.$h,round($all["shuijin"],2));
		$objPHPExcel->getActiveSheet()->setCellValue('S'.$h,round($all["he_hanshui"],2));
		$objPHPExcel->getActiveSheet()->setCellValue('T'.$h,round($all["he_hanshui"],2));

		$h+=2;
		$objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"支付信息");
        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:Y{$h}");
         $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->getStartColor()->setARGB('0099CCFF');
        $h++;
        $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"总含税金额:".round($all["he_hanshui"],2)."元；已支付金额:".round($all["zhifu_jine"],2)."元；未付金额:".round($all["weifu"],2)."元");
        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:Y{$h}");
        $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->getStartColor()->setARGB('00CCCCCC');

        	//支付详细
    	$zhifus=Db::table("ap_zhifu")->alias("az")
        ->join("employee ec","az.z_users_id=ec.id","LEFT")
        ->where(["az.is_deleted"=>0,"az.is_actived"=>1,"az.hexiao_id"=>$hid])
        ->field("az.zfpz,ec.em_name as cname,az.zhifu_day,az.zfjin,az.remark")
        ->select();
       	for($i=0;$i<count($zhifus);$i++){
       		$h++;$zf=$zhifus[$i];
       		  $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"支付凭证:{$zf["zfpz"]}; 支付人:{$zf["cname"]} ; 支付时间:{$zf["zhifu_day"]} ; 支付金额:".round($zf["zfjin"],2)."元 ; 支付备注:{$zf["remark"]}");
        		$objPHPExcel->getActiveSheet()->mergeCells("A{$h}:Y{$h}");
       
       	}



         $h+=2;
			 $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,"审批意见");
        $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:Y{$h}");
         $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
        $objPHPExcel->getActiveSheet()->getStyle("A{$h}")->getFill()->getStartColor()->setARGB('0099CCFF');
        $logs=$this->getlog(15,$hid);
         for($i=0;$i<count($logs);$i++){
            $h++;
            if($logs[$i]["COMMENTS"])
                $str="{$logs[$i]["USERNAME"]} 审批动作：{$logs[$i]["MEMO"]}；审批意见：{$logs[$i]["COMMENTS"]}(审批时间：{$logs[$i]["ACTIONTIME"]})";
            else
                $str="{$logs[$i]["USERNAME"]} 审批动作：{$logs[$i]["MEMO"]}；审批意见：无 (审批时间：{$logs[$i]["ACTIONTIME"]})";
             $objPHPExcel->getActiveSheet()->setCellValue('A'.$h,$str);
            $objPHPExcel->getActiveSheet()->mergeCells("A{$h}:Y{$h}");
        }
             $styleArray = array(  
        'borders' => array(  
            'allborders' => array(  
                //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框  
                //'color' => array('argb' => 'FFFF0000'),  
            ),  
        ),  
    );  
   $objPHPExcel->getActiveSheet()->getStyle('A1:Y'.$h)->applyFromArray($styleArray);//这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪
         $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
 		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('V')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('W')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('X')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('Y')->setWidth(20);

        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
           ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=AP费用核销申请表完整版.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        
        $objWriter->save('php://output');
    }
}